我想向yii2和FilterWhere()添加子查询。请在下面查看我的代码
$query->andFilterWhere(['between', 'year_id', $this->year_start,$this->year_end])
我尝试过这样的事情。我想按年份过滤结果。但是问题是我只在表中保存了year_id,这是与year到另一个表的外键。然后如何添加它搜索。我不能像上面那样给出。因为年份不在同一张表中。
在您的搜索模型中。您必须添加这样的新变量:
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
它必须遵循逻辑基础。您可以更新