Laravel从关系中获得第一项的模型

I have:

public function getThumbnail($id) {
    $thumbnail = Product::find($id);
    if($thumbnail) {
        return $thumbnail->with('images')->get();
    } else {
        return response()->json('That cake does not exist.');
    }
}

Which returns the product with any images attached it to.

However, I would like it to only return images marked "primary". Something like this (pseudo):

return $thumbnail->with('images->isPrimary')->get();

How can I achieve this?


What about:

return $thumbnail->with(['images' => function ($query) {
            $query->where('is_primary', 1);
        }])->get();

You should use the whereHas operator in order to obtain all Products that have at least one primary image, as follows:

$thumb = Product::whereHas('images', function ($query) {
    $query->where('primary', 'true');
})->get();

More on Querying Relationships here.


UPDATE

After finding your Product by id, if you just want to show images that are primary, you may use Query Scopes:

In your Image class:

public function scopePrimaries ($query) {
  return $query->where('is_primary', 1);
}

So then you can fetch them like this:

$primaryThumbs = $product->images()->primaries()->get();

I did this which seems to work:

public function getThumbnail($id)
{
    $thumb = Product::find($id);
    if ($thumb) {
        return $thumb->with(['images' => function ($query) {
            $query->where('is_primary', 1);
        }])->whereHas('images', function ($query) {
            $query->where('is_primary', 1);
        })->get();
    } else {
        return response()->json([]);
    }
}

Is there a simpler way?