table join with model relation

Hello, this is probably a stupid question but I can’t figure out how to get a column value from a joined table on my model.

For example, I have this query…




$orderItems = OrderItem::find()->where(['order_id' => $this->id])->joinWith('booking')->all();



the booking table has a column called description that I need. I would like to do something like this…




foreach($orderItems as $item)

{

    echo $item->description;

}



However, that obviously does not work because my OrderItem model does not have a ‘description’ attribute. The description attribute is part of the booking table. How can I accomplish this?




foreach($orderItems as $item)

{

    echo $item->booking->description;

}



Thanks, I forgot I could do it like that.

However, wouldn’t this create unnecessary database calls? Every time you call


$item->booking->description;

you would be querying the database again? To avoid unnecessary overhead shouldn’t there be a way to get everything you need in one query?

You could avoid eager loading of booking, setting second parameter to false:




$orderItems = OrderItem::find()->where(['order_id' => $this->id])->joinWith('booking', false)->all();



Thanks for the reply again but adding the false parameter to the joinWith method still didn’t return the data from the booking table.

The only way I have found, that actually worked, was to return the data as an array like so…


OrderItem::find()->where(['order_id' => 1])->joinWith('booking')->asArray()->all();

I think, You also can write query as like below,

If you are joining two tables that means there must be one column which is same in both tables, So you can join on that particular column.

The query will be like…

$query= (new \yii\db\Query())

     ->select('description')


     ->from('OrderItem o')


     ->join('inner join', 'booking b', 'o.order_id=b.order_id')


     ->where(['order_id' => 1])


     ->all();

If booking table has any relation with then just write relation,plz post your table structure so it will usefull for us to resolve ur issue.