php - fetch only X Product Model via eager loading in a ManyToMany Product Category relationship -
i have manytomany relationship between category , product model.
product model :
class product extends model { protected $primarykey = 'product_id'; public function categories () { return $this->belongstomany('app\category', 'category_product', 'product_id', 'cat_id'); } }
and category model :
class category extends model { protected $primarykey = 'cat_id'; public function products (){ return $this->belongstomany('app\product','category_product','cat_id','product_id'); } }
now , want fetch last 4(for example) products of each category. write :
$categories = category::with([ 'products' => function($query){ $query->select('products.product_id')->orderby('created_at','desc')->take(4); } ])->get();
but not work , return unexpected products count?
how can that?
if want last x number of products per category can try :
category::with(['products' => function($query) { $query->orderby('updated_at','desc')->take(x); }])->get();
this should return collection of categories in should have no more desired number of products per category.
hope helps.
Comments
Post a Comment