请有人解释一下 Yii2 SearchModel
中的 search
方法是如何工作的?我使用 Gii 生成了它。这里是:
public function search($params){
$query = MyModel::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
if (!($this->load($params) && $this->validate())) {
return $dataProvider;
}
$this->addCondition($query, 'att1');
$this->addCondition($query, 'att1', true);
$this->addCondition($query, 'att2');
$this->addCondition($query, 'att2', true);
return $dataProvider;
}
我是这样调用它的:
$search = new MyModelSearch();
$myModels = $search->search(['att3' => '3']);
无论我在调用 search
时使用什么属性,我总是得到相同的结果 - 即表中的所有条目。我在这里遗漏了一些我不明白的东西。
任何帮助将不胜感激。谢谢。
最佳答案
Gii生成的search()
函数使用ActiveRecord::load()
设置搜索参数:
load()
gets the'FormName'
from the model'sformName()
method (which you may override), unless the$formName
parameter is given. If the form name is empty,load()
populates the model with the whole of$data
, instead of$data['FormName']
.
所以你应该试试:
$myModels = $search->search(['MyModelSearch'=>['att3'=>3]]);
或者
$myModels = $search->search([$search->formName()=>['att3'=>3]]);
当然,在 search()
函数中的 att3
属性上添加条件:
$this->addCondition($query, 'att3');
但是如果你真的想使用 $myModels = $search->search(['att3' => '3']);
那么你应该简单地替换 $this-> load($params)
与 $this->load($params, '')
.
关于php - Yii2 SearchModel 中的 search() 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21779085/