rafiaTech rafiaTech - 2 months ago 6
PHP Question

Laravel get single record from relationship for each part

I have two table parts and images. Each part has multiple images. I would like to display all the parts with their images but I only want to display single image. So if a part has multiple images I would like to display one image. Here is my query

return Part::with(['images'=> function($q)
{
$q->limit(1);
}])->get();


The above query only displays one image. But i would like to display one image for each part.

Thank you

Answer

Its not possible with "with", as its act like below:

select * from parts

select * from images where id in (1, 2, 3, 4, 5, ...) limit 1

Instead you can do this in a loop like below:

foreach ( Parts::get() as $Part ) {
    $FirstImageOfPart = $Part->images()->first();
    // ...
}