我有一个数据库,用于存储拍摄内容及其标签。它们与多对多关系有关,我使用联结表来存储关系。知道我想实现一个搜索,其中可以指定N个标签,并且只应返回具有这些N个标签的拍摄。我已经实现了搜索一个标签,但我不知道如何搜索N标签。如果可能的话,我想尽可能做到最好。
这是我在模型中使用的关系:
/**
* @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;
}
}
答案 0 :(得分:0)
会是这样的吗?
Shoot::find()->joinWith('tags')->where(['tag.name' => ['tag1', 'tag2', 'tag3']]);
这将使用您已设置的规则连接数据透视表和标记表,并使用IN
语句按标记名称进行过滤