[英]Laravel get model with first item from relationship
我有:
public function getThumbnail($id) {
$thumbnail = Product::find($id);
if($thumbnail) {
return $thumbnail->with('images')->get();
} else {
return response()->json('That cake does not exist.');
}
}
它将返回带有任何图像的产品。
但是,我只希望返回标记为“主要”的图像。 像这样的东西(伪):
return $thumbnail->with('images->isPrimary')->get();
我该如何实现?
关于什么:
return $thumbnail->with(['images' => function ($query) {
$query->where('is_primary', 1);
}])->get();
您应使用whereHas
运算符,以获取具有至少一个primary
映像的所有Products
,如下所示:
$thumb = Product::whereHas('images', function ($query) {
$query->where('primary', 'true');
})->get();
更多关于查询关系的信息 。
UPDATE
按id
查找Product
后,如果您只想显示primary
图像,则可以使用Query Scopes :
在您的Image
类中:
public function scopePrimaries ($query) {
return $query->where('is_primary', 1);
}
因此,您可以像这样获取它们:
$primaryThumbs = $product->images()->primaries()->get();
我这样做似乎可行:
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([]);
}
}
有没有更简单的方法?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.