rafiaTech rafiaTech - 1 year ago 59
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)

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

Thank you

Answer Source

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();
    // ...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download