2
votes

So I have a products table and a categories table and a pivot table.

Product (products)

-- id

-- name

Category (categories)

-- id

-- name

CategoryProduct (category_product)

-- category_id

-- product_id

I want to get all products that belong to a certain category, I have managed to get it by doing the following query:

$products = Category::find(3)->products;

But how can I access it off the product model?

$products = Product::?
1

1 Answers

1
votes

You need the whereHas clause. https://laravel.com/docs/5.4/eloquent-relationships#querying-relationship-existence

$products = Product::whereHas('categories', function ($query) {
    return $query->where('id', 3);
})->get();

Or you can do it with a join instead.

$products = Product::select('products.*')
    ->join('category_product', 'products.id', '=', 'category_product.product_id')
    ->where('category_product.category_id', 3)
    ->groupBy('products.id')
    ->get();