按GridView中的相关字段筛选
我用过教程,它很棒 一切正常,但在添加“场景3步骤”后,我陷入了困境: 它触发mysql查询,如下所示:按GridView中的相关字段筛选,gridview,yii2,yii2-advanced-app,Gridview,Yii2,Yii2 Advanced App,我用过教程,它很棒 一切正常,但在添加“场景3步骤”后,我陷入了困境: 它触发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 "%%" O
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')]
]);
不要忘记在gridview中显示parent.fullName
,而不是parentName
阅读更多信息:问题已解决
之前:
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 : ' -- ' ;
}
请修改教程link@soju:Link update我没有得到你的答案,我有两个模型,简单模型和搜索模型,函数attributeLabels(){在简单模型中,函数规则()在搜索模型中,现在返回数组合并(parent::attributes(),['parent.fullName']);的含义是什么?函数attributes()是什么?
public function getParentName() {
return (!empty ($this->parent->fullName)) ? $this->parent->fullName : ' -- ' ;
}