I have a ManyToMany relationship between Category and Product Model.
Product Model is like this :
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 is :
class Category extends Model
{
protected $primaryKey = 'cat_id';
public function products (){
return $this->belongsToMany('App\Product','category_product','cat_id','product_id');
}
}
Now , I want to fetch only last 4(for example) products of each Category. for that I write this :
$categories = Category::with([
'products' => function($query){
$query->select('products.product_id')->orderBy('created_at','desc')->take(4);
}
])->get();
But this does not work properly and return unexpected products count?
How Can I do that?