假设一个类别有许多产品。
我希望加载所有产品类别,然后为每个类别加载三个产品。
在《拉拉威尔5》中,这怎么可能呢?这似乎是不可能的。
换言之,我希望限制急切的工作量。
我试过这个:
$categories = Category::with([
'images',
'products' => function($query) {
$query->take(3); // THIS does NOT work...
}
])->get();
它产生这样的输出:
select *
from `products`
where `products`.`category_id` in ('1', '2', '3', '4', '5') limit 3
有什么建议吗?
我添加了一个扩展原始关系的关系。
public function products() {
return $this->hasMany( 'Products' );
}
public function firstProducts() {
return $this->products()->limit( 3 );
}
然后我可以打电话。
$categories = Category::with(['images','firstProducts'])->get();
可能还有其他方法可以实现这一点。你可以查看范围,但为了快速解决问题,这在修补程序中有效。