I have categories related to each other in a tree. Each category hasMany
children. Each end category hasMany
products.
The products also belongsToMany
different types.
I want to eager load the categories with their children and with the products but I also want to put a condition that the products are of a certain type.
This is how my categories Model looks like
public function children()
{
return $this->hasMany('Category', 'parent_id', 'id');
}
public function products()
{
return $this->hasMany('Product', 'category_id', 'id');
}
The Product Model
public function types()
{
return $this->belongsToMany(type::class, 'product_type');
}
In my database I have four tables: category, product, type, and product_type
I've tried eager loading like so but it loads all the products and not just the ones that fulfil the condition:
$parentLineCategories = ProductCategory::with('children')->with(['products'=> function ($query) {
$query->join('product_type', 'product_type.product_id', '=', 'product.id')
->where('product_type.type_id', '=', $SpecificID);
}]])->get();
Eager loading is super simple using Laravel and basically prevents you from encountering the N+1 problem with your data. This problem is caused by making N+1 queries to the database, where N is the number of items being fetched from the database.
One-to-many (Polymorphic) When a single model belongs to more than one type of model on a single association is known as one-to-one polymorphic relationship. For example, if we have three tables, posts, users, and photo table, where photo table represents the polymorphic relation with the users and posts table.
One To One (Polymorphic) One To Many (Polymorphic) Many To Many (Polymorphic)
Instead of the current query, try if this fits your needs. (I modified my answer as follows with your comment)
$parentLineCategories = ProductCategory::with([
'children' => function ($child) use ($SpecificID) {
return $child->with([
'products' => function ($product) use ($SpecificID) {
return $product->with([
'types' => function ($type) use ($SpecificID) {
return $type->where('id', $SpecificID);
}
]);
}
]);
}
])->get();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With