Getting related model attribute value

I apologize, I should be able to do this, but for some reason am totally struggling with this today.

I have a model which includes

    public function getItem()
    {
        return $this->hasOne(LstItems::className(), ['ItemId' => 'ItemId']);
    }

In my index view, I have a GridView column like

            [
                'content' => function($model,$key) {
                    return Html::button('<i class="glyphicon glyphicon-search"></i>', 
                    [
                        'class' => 'btn btn-info btn-xs modalButton', 
                        'value'=>Url::to('index.php?r=lst-employees/update').'&id='.$key, 
                        'title'=>'Updating . $model->getItem()->ItemDescription,
                    ]) ;
                },
                'label' => 'View',
            ],

in which I am trying to use the model function to return the related attribute value, but I can’t get it functional. No matter what I try, my syntax is always wrong.

What is the proper way to write

$model->getItem()->ItemDescription

So it returns the value of the ItemDescription from the LstItems table which has the same ItemId?

See https://www.yiiframework.com/doc/guide/2.0/en/db-active-record#accessing-relational-data

Note: While this concept looks similar to the object property feature, there is an important difference. For normal object properties the property value is of the same type as the defining getter method. A relation method however returns an yii\db\ActiveQuery instance, while accessing a relation property will either return a yii\db\ActiveRecord instance or an array of these.

$customer->orders; // is an array of `Order` objects
$customer->getOrders(); // returns an ActiveQuery instance

So, your statement getItem() in $model->getItem()->ItemDescription returns ActiveQuery to further customization, add conditions etc.
What you need is $model->item->ItemDescription

1 Like

Problem solved! My syntax is fine, it’s an issue with my test data!!! Stupid me. Sorry to have waste people’s time on this.

@BartQ76
You are entirely correct, $model->item->ItemDescription, works perfectly.