2
votes

I have Products, SubCategories, Categories relationship..

in Category model where I defined hasManyThrough relationship :

public function products()
{
    return $this->hasManyThrough('Products','SubCategory');
}

How do I display only 4 products on each category?

$products = Category::with('products')->get()

I already add take(2) or limit(2) on hasManyThrough relationship, but the query limit overall products, not by subcategory. Here is the query log :

select products.*, subcategories.category_id from products inner join subcategories on subcategories.id = products.subcategory_id where subcategories.category_id in (?, ?, ?, ?, ?, ?) limit 4
1

1 Answers

0
votes

I dont't think you can set hasManyTrough relation limits, but you can separate your relations and set own limits for them:

Category has subcategories:

public function subcategories()  
{
    return $this->hasMany('Subcategory')->limit(2);
}

Subcategories has products:

public function products()  
{
    return $this->hasMany('Product')->limit(4);
}

Then you can call:

Category::with('subcategories.products')->get();