我使用过 http://www.yiiframework.com/wiki/621/filter-sort-by-calculated-lated-fields-in-gridview-yii-2-0/ 教程,它很棒。
一切正常,但在添加“场景 3 步骤”后我陷入困境:
// filter by parent name
$query->joinWith(['parent' => function ($q) {
$q->where('parent.first_name LIKE "%' . $this->parentName . '%" ' .
'OR parent.last_name LIKE "%' . $this->parentName . '%"');
}]);
它会触发 mysql 查询,例如:
SELECT COUNT(*) FROM `person` LEFT JOIN `country` ON
`person`.`country_id` = `country`.`id` LEFT JOIN `person` `parent` ON
`person`.`id` = `parent`.`parent_id` WHERE parent.first_name LIKE "%%" OR
parent.last_name LIKE "%%"
这不会返回任何记录。
我尝试过类似的事情:
if ($this->parentName) {
$query->joinWith(['parent' => function ($q) {
$q->where('parent.first_name LIKE "%' . $this->parentName . '%" ' .
'OR parent.last_name LIKE "%' . $this->parentName . '%"');
}]);
}else {
$query->joinWith('parent');
}
但这给了我一个错误,例如:
Trying to get property of non-object
1. in /var/www/html/advanced/common/models/Person.php at line 54
/* Getter for parent name */
public function getParentName() {
return $this->parent->fullName; // its 54th line
}
本教程应该更新。
无需为父名称创建 getter,您应该将其添加到您的搜索模型中:
public function attributes()
{
// add related fields to searchable attributes
return array_merge(parent::attributes(), ['parent.fullName']);
}
public function rules()
{
return [
...
['parent.fullName', 'safe'],
...
];
}
然后简单地修改您的搜索查询,如下所示:
$query->andFilterWhere([
'OR',
['LIKE', 'parent.first_name ', $this->getAttribute('parent.fullName')]
['LIKE', 'parent.last_name ', $this->getAttribute('parent.fullName')]
]);
并且不要忘记在网格视图中显示
parent.fullName
而不是 parentName
。
了解更多:http://www.yiiframework.com/doc-2.0/guide-output-data-widgets.html#working-with-model-relations
问题解决了
之前:
Trying to get property of non-object
1. in /var/www/html/advanced/common/models/Person.php at line 54
public function getParentName() {
return $this->parent->fullName; // its 54th line
}
之后
public function getParentName() {
return (!empty ($this->parent->fullName)) ? $this->parent->fullName : ' -- ' ;
}