如何在yii2过滤器中添加子查询

问题描述 投票:0回答:1

我想向yii2和FilterWhere()添加子查询。请在下面查看我的代码

$query->andFilterWhere(['between', 'year_id', $this->year_start,$this->year_end])

我尝试过这样的事情。我想按年份过滤结果。但是问题是我只在表中保存了year_id,这是与year到另一个表的外键。然后如何添加它搜索。我不能像上面那样给出。因为年份不在同一张表中。

php search yii2
1个回答
0
投票

在您的搜索模型中。您必须添加这样的新变量:

class ModelSearch extends Requests
{
    public $year_start;
    public $year_end;
    .....

最好在规则中将此变量设置为safe

public function rules()
{
    return [
        ....
        [['year_start', 'year_end'], 'safe'],
    ];
}

并且在search方法中,必须设置与joinWith的关系。在joinWith条件后执行此操作。像这样:

if (!$this->validate())

然后您可以添加新的过滤器以根据您的关系进行搜索。

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;
}
$query->joinWith('years'); // relation table

它必须遵循逻辑基础。您可以更新

© www.soinside.com 2019 - 2024. All rights reserved.