ActiveRecord - get foreign attribute after table join

I have looked all over the place but have not found an answer to this question. I would expect it to be very easy but I can’t figure it out…

I use a table join to join my "booking" and "order_item" tables like this,

$bookings = Booking::find()->joinWith('orderItem')->all();

I’m trying to get an attribute from the ‘OrderItem’ table out of the result like this,

            foreach($bookings as $booking)


                echo $booking->price;


The “price” attribute is part of the OrderItem table. However, when I try to get the attribute like this it says… ‘Getting unknown property: common\models\ar\Booking::price’

How can I get an attribute from a foreign table in my booking model after the table join?

Did you set the relation "orderItem" ?

Yes I did. The query works just fine but I can’t figure out how to get an attribute out of the joined table. I have also tried using


but still get the same error.

ah, right… you need to use the relation… so it should be $booking->orderItem->price

I just tried using,


and that worked. Is this the correct way to be doing it?

But doing it that way defeats the whole purpose of the table join in the first place. Instead of having to issue extra queries every time via the "lazy load" method we should be able to issue one query then reference the foreign attributes.

If I do it the way you suggested then there is no point in having the table join in the first place. It creates additional queries and unnecessary overhead if we use the "lazy load" method you suggest.

yes… when data is eager load there will not be another queries when you use the relation… for more information check this wiki article -

Thank you for that link. It helped a-lot. I will keep the "eager load" verse the "lazy load" in mind for next time.

That link is for Yii 1.1 but I’m assuming it applies to Yii2 as well. So the trick with eager loading is to use the “with” method. Is that correct?