0
votes

I have used http://www.yiiframework.com/wiki/621/filter-sort-by-calculated-related-fields-in-gridview-yii-2-0/ tutorial and its great.

Everything is working fine but I get stuck after adding "Scenario 3 Steps":

// filter by parent name
$query->joinWith(['parent' => function ($q) {
        $q->where('parent.first_name LIKE "%' . $this->parentName . '%" ' .
        'OR parent.last_name LIKE "%' . $this->parentName . '%"');
}]);

it fires mysql query like:

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 "%%"

Which doesn't return any records.

I have tried something 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');
        }

but that's giving me an error like:

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
Please fix the tutorial linksoju
@soju : Link updatedEr.KT

2 Answers

3
votes

This tutorial should be updated.

No need to create a getter for parent name, you should add this to your search model :

public function attributes()
{
    // add related fields to searchable attributes
    return array_merge(parent::attributes(), ['parent.fullName']);
}

public function rules()
{
    return [
        ...
        ['parent.fullName', 'safe'],
        ...
    ];
}

And then simply modify your search query like this :

$query->andFilterWhere([
    'OR',
    ['LIKE', 'parent.first_name ', $this->getAttribute('parent.fullName')]
    ['LIKE', 'parent.last_name ', $this->getAttribute('parent.fullName')]
]);

And don't forget to display parent.fullName in your gridview instead of parentName.

Read more : http://www.yiiframework.com/doc-2.0/guide-output-data-widgets.html#working-with-model-relations

-1
votes

Problem solved

Before:

    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
    }

After

    public function getParentName() {
        return (!empty ($this->parent->fullName)) ? $this->parent->fullName : ' -- ' ;        
    }