John Davidson

php - Return data from 2 pivot tables

0 comments
Message:


I have products, categories, sizes tables and also have 2 pivot tables named category_product and product_size in my database.
I am trying to get products belong to a specific category and I need to filter them by size.


I have tried this but I am getting all sizes...


$category = Category::where('slug', $slug)->first();
$products = $category->products()
->with('sizes')
->whereHas('sizes', function($q) use($size_id) {
$q->where('size_id', '=', $size_id);
})
->paginate(12);

Product model


public function categories()
{
return $this->belongsToMany(Category::class);
}

public function sizes()
{
return $this->belongsToMany(Size::class);
}

Category model


public function products()
{
return $this->belongsToMany(Product::class);
}

Size model


public function products()
{
return $this->belongsToMany(Product::class);
}


My Answer:
To filter products by size for a specific category, you can modify your query as follows:

php
$category = Category::where('slug', $slug)->first();
$products = $category->products()
->whereHas('sizes', function($q) use($size_id) {
$q->where('size_id', '=', $size_id);
})
->paginate(12);


This query will retrieve products that belong to the specific category and have the specified size. The `with('sizes')` method is not necessary in this case because you are already filtering the products by size.

Rate this post

3 of 5 based on 1547 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us