繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM