我在类别和产品模型之间有ManyToMany关系。只抓取X产品模型通过在ManyToMany产品类别关系中的热切加载
产品模式是这样的:
class Product extends Model
{
protected $primaryKey = 'product_id';
public function categories()
{
return $this->belongsToMany('App\Category', 'category_product', 'product_id', 'cat_id');
}
}
而且分类型号是:
class Category extends Model
{
protected $primaryKey = 'cat_id';
public function products(){
return $this->belongsToMany('App\Product','category_product','cat_id','product_id');
}
}
现在,我想提取每个类别的只有最后4(例如)产品。为此我写这个:
$categories = Category::with([
'products' => function($query){
$query->select('products.product_id')->orderBy('created_at','desc')->take(4);
}
])->get();
但是,这不能正常工作,并返回意外的产品数?
我该怎么做?
你可以试试这个$ categories = Category :: all(); (0) - > take(4) - > get()() - > orderBy('product_id','DESC') - > skip(0) - > ; }更改相关类别模型的类名称。 –