Yii2 多对多查找具有多个条件的模型
我有一个数据库,我在其中存储了芽和它们的标签。它们与多对多关系相关,我使用连接表来存储这些关系。知道我想要实现一个搜索,其中a可以指定N个标记,并且只应该返回具有这些N个标记的快照。我已经实现了搜索一个标记,但是我不知道如何搜索N个标记。如果可能的话,我会尽可能地做到这一点 以下是我在模型中使用的关系:Yii2 多对多查找具有多个条件的模型,yii2,many-to-many,Yii2,Many To Many,我有一个数据库,我在其中存储了芽和它们的标签。它们与多对多关系相关,我使用连接表来存储这些关系。知道我想要实现一个搜索,其中a可以指定N个标记,并且只应该返回具有这些N个标记的快照。我已经实现了搜索一个标记,但是我不知道如何搜索N个标记。如果可能的话,我会尽可能地做到这一点 以下是我在模型中使用的关系: /** * @return \yii\db\ActiveQuery */ public function getShootTags() { return $this->hasM
/**
* @return \yii\db\ActiveQuery
*/
public function getShootTags()
{
return $this->hasMany(ShootTag::className(), ['shoot_id' => 'shoot_id']);
}
public function getTags()
{
return $this->hasMany(Tags::className(), ['tag_id' => 'tag_id'])->via('shootTags');
}
我的搜索模型如下所示:
namespace app\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Shoots;
/**
* ShootsSearch represents the model behind the search form of
`app\models\Shoots`.
*/
class ShootsSearch extends Shoots
{
public $tag;
/**
* @inheritdoc
*/
public function rules()
{
return [
[['shoot_id', 'date'], 'integer'],
[['filename', 'tag'], 'safe'],
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$query = Shoots::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'shoot_id' => $this->shoot_id,
'date' => $this->date,
]);
$query->andFilterWhere(['like', 'name', $this->tag]);
$query->andFilterWhere(['like', 'filename', $this->filename]);
return $dataProvider;
}
}
像这样的东西对你有用吗
Shoot::find()->joinWith('tags')->where(['tag.name' => ['tag1', 'tag2', 'tag3']]);
这将使用您已设置的规则连接数据透视表和标记表,并在语句中使用
按标记名进行筛选是否需要所有这些N个标记的记录,或者一个就足够了?添加您正在使用的控制器/操作
和所涉及的视图,这可以很容易地完成,但直到提供了所有信息,这使得在提供解决方案时输入的信息更少