Relations in Models do not work

Hi everyone,

still trying to get the grip of Yii2.

I have two tables with a standard Many:1 relation. In the model of the “many” table, I’d like to access the relation table.

I use the following code in the model:


    public function getItems()

    {

        return $this->hasOne(Items::className(), ['i_no' => 'iv_item_no']);

    }


    public function getName() {

    	return (isset ($this->iv_name) == true ? $this->iv_name : $this->items->i_name);

    

    }

The function getName should get the name (table1.iv_name) from the model’s table, but if that doesn’t exist take the name from the relationally linked table2 (items.i_name).

My models seems to be fine so far (mostly generated by GII anyway) as I can access the relational data in a gridview via "items.i_name". However, for the "return" line in above statement I always get "Trying to get property of non-object". So somehow "items" is not initialised as an object… but why not?

I followed this tutorial and can’t spot my mistake:

http://www.yiiframework.com/wiki/621/filter-sort-by-calculated-related-fields-in-gridview-yii-2-0/#hh10

Regards,

Jan

Solved it!

The problem was the first line in my gridview which are the "search fields". In those lines the object "items" is not defined as there is no relation. a simple "if isset ()" solved the issue…

I was not aware that the "empty line" in the gridview is also represented by an ActiveRecord instance.

Regards and thank for the views,

Jan