繁体   English   中英

Eloquent 关系 – 如何从相关的 model 中获取最后 4 个?

[英]Eloquent relations – how to get the last 4 from a related model?

我要求创建一个页面,显示所有类别的列表以及每个类别的最后 3 个产品。

类别和产品之间存在关系。

类别 Model:

public function products(){
    return $this->hasMany('App\Models\Product');
}

产品 Model

public function category(){
    return $this->belongsTo('App\Models\Category');
}

Controller function 应该返回结果

return Category::with(["products" => function($res) {
    $res->take(3);
}])->paginate(2);

上面的代码只为所有类别返回 3 个产品,而不是为每个类别获取 3 个产品

您可以在类别 Model 中定义另一种关系方法,如下所示,

public function latestproducts(){
    return $this->hasMany('App\Models\Product')->orderBy('id', 'desc')->take(3)->get();
} 

这只是一个快速修复。 可能还有其他一些解决方案。

谢谢!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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