Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
How to use related() via ORM in one to many (has many)?
  • I have products table
    This products table has many 'product_images' items.

    1 product -> many images.

    If i use \Model_Products::find('all');
    I can loop image in the product list page.

    But, if i use \Model_Products::query()->related('product_images')->where('...conditions...')->get();
    I can still list products but cannot loop image in product list.
    The image show only one.

    Model _has_many and _belongs_to was set correctly. (because it works with find('all') but not with query()->related();)

  • If you do a find('all') like that, the ORM will use lazy loading to get the related information when you request it. That means in your loop it will fire a new query for every product to get the images.

    When you use 'related' (you can do that in a find 'all' too) you switch to eager loading, and the ORM will generate a JOIN query to get all data, which in most cases is more efficient.

    Both queries should give you the same output, so I can't say what the cause is, I have never seen this.

    Enable the DB profiler, and check what SQL is generated for that query, and see if you can spot something odd?
  • Does group by required in this case? (many related tables)
  • HarroHarro
    Accepted Answer
    No, absolutely not. A group_by will destroy the result, you need the individual child records.

    So if you have 1 product and 4 related image records, the JOIN should produce 4 records (in which the product part is repeated), the ORM's hydration logic will split that result back into 1 product object and 4 related image objects.
  • thank you very much :)

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion