Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 2 years ago.
0

in case of this, I guess you still end up with two queries, so there is no point in that.

$products = Category::with('product')->find($category->id);

To get only one picture query should look smth like this, though I did not test this:)

Product::with(['picture' => function($query){
    $query->take(1);
}])->get();
Last updated 2 years ago.
0

Limit on eager loading query for a SINGLE model just like @luknei said, but to clarify, if you use such statement for more than just one model like in the example:

Product::with(['picture' => function($query){
    $query->take(1);
}])->get();

then you will end up with only one related picture (in total, not one per Product), as it's going to use LIMIT 1 on the query.

Now, this part:

$products = Category::with('product')->find($category->id);

is not going to return products, but category with appended related products.

So for a single category I'd suggest using this code:

$category = Category::find($category_id);
$product = $category->products()->first();

This way you have exactly the same number of queries and it's much more clean.

Last updated 2 years ago.
0

ok, thanks a lot - i'm now just grabbing all and breaking my foreach loop in the view (possibly not best practice but effective)

Second part

$products = Category::with('product')->find($category->id);

@jarektkaczyk er..thats not true, i made a mistake,and it definately does return products, and in fact complete with images, so that part of the question has resolved itself

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.