Get all possible elements from belongsToMany Relationship Hello community,
I have 3 tables
products
categories
category_product
Given I have a collection with categories
$category = Category::findMany([1, 2]);
I want to get all possible products from both categories in a collection
So far i am creating a foreach loop and combining arrays but want a cleaner way if possible
Thanks in advance.
Hi @manojow
I'm not sure if I understand your question...but it seems to me that maybe just Eager Loading the Products should be enough to achieve what you want:
$category = Category::with('products')->findMany([1, 2]);
This of course, provided that you have the corresponding relationship defined for your Products at your Category model.
ref: https://laravel.com/docs/master/eloquent-relationships#eager-loading
@marianomoreyra Thanks for the reply:
In your case you are considering the product collection separately in each category. I need all products from category 1 and 2 together in the same collection
I dropped my loop and now I am using this logic
Product::whereIn(
'id',
CategoryProduct::whereIn('category_id', [1, 2])->pluck('product_id')
)->get();
Where CategoryProduct is a pivot model class that I just created. I think thats it.
Hi @manojow
$products = Product::whereHas('categories', function ($query) {
$query->whereIn('id', [1, 2]);
});
Please sign in or create an account to participate in this conversation.