具有多个条件的多对多查找模型



我有一个数据库,我在其中存储拍摄及其标签。它们与多对多关系相关,我使用连接表来存储关系。知道我想实现一个搜索,其中 a 可以指定 N 个标签,并且只应返回具有这 N 个标签的拍摄。我已经实现了搜索一个标签,但我不知道如何搜索 N 个标签。如果可能的话,我想以最 yii 的方式做到这一点。

这是我在模型中使用的关系:

/**
 * @return yiidbActiveQuery
 */
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 appmodels;
use Yii;
use yiibaseModel;
use yiidataActiveDataProvider;
use appmodelsShoots;
/**
* ShootsSearch represents the model behind the search form of 
`appmodelsShoots`.
*/
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']]);

这会将数据透视表和标签表与您设置的规则连接起来,并使用 IN 语句按标签名称进行过滤

最新更新