2

I have 3 model Price, Description and Product

the Description model has relationship on Price model and Price model has relationship on Product.

Can I call the product when I try to get it on Description model using the relationship of Price?

here's what I'm trying to do

$description = Description::model()->with('Price')->findAll();
// after that I want to call the product which is on price.

they're all connection using their id. product_id, description_id and price_id

How can I achieve this? is there a way?

niac
  • 33
  • 2
  • 17
Jovs
  • 852
  • 7
  • 23

1 Answers1

1

First of all, JFYI when you use with() method to establish join part from ActiveRecord's query builder, please just double check also the relations() method from the specific AR model to see the actual defined relations. I pointed to this because defining relations into model and access them in later stage via query builder is case-sensitive.

Back to your question.

If you have already fetched your Description model joined eagerly with() your Price model, when you call $description->price->product, behind the scenes ActiveRecord will perform the so-called lazy-loading approach.

According to Yii 1.1 docs -> https://www.yiiframework.com/doc/guide/1.1/en/database.arr :

  1. Performing Relational Query
    The simplest way of performing relational query is by reading a relational property of an AR instance. If the property is not accessed previously, a relational query will be initiated, which joins the two related tables and filters with the primary key of the current AR instance. The query result will be saved to the property as instance(s) of the related AR class. This is known as the lazy loading approach, i.e., the relational query is performed only when the related objects are initially accessed.

The example below shows how to use this approach:

// retrieve the post whose ID is 10
$post = Post::model()->findByPk(10);
// retrieve the post's author: a relational query will be performed here
$author = $post->author;

Hope this helps.

G.Spirov
  • 198
  • 9
  • That's just the normal way I mean the single with of relations model method. what I want is more like nested relation model method. anyway I already figure out the answer for my question. Thank you so much for the effort. – Jovs Apr 15 '20 at 14:05
  • Anytime. I will add some clarification in order to be fully informative nevertheless you may have end up here as you told you figured out the issue. If you especially want to eager load nested hierarchical relations, you can do it like this way: $description = Description::model()->with('price.product')->findAll(); – G.Spirov Apr 15 '20 at 15:55
  • Noted on that. Thanks – Jovs Apr 15 '20 at 15:57