按GridView中的相关字段过滤

时间:2015-02-26 10:06:55

标签: gridview yii2 yii2-advanced-app

我使用了http://www.yiiframework.com/wiki/621/filter-sort-by-calculated-related-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
    }

2 个答案:

答案 0 :(得分:3)

应该更新本教程。

无需为父名称创建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

了解详情:http://www.yiiframework.com/doc-2.0/guide-output-data-widgets.html#working-with-model-relations

答案 1 :(得分:-1)

问题解决了

<强>之前:

    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 : ' -- ' ;        
    }