Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eager load relationships in laravel with conditions on the relation

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();
like image 665
Suemayah Eldursi Avatar asked Jan 16 '17 15:01

Suemayah Eldursi


People also ask

How eager loading works in Laravel?

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.

What are different types of relationships we can define on models in Laravel?

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.

How many types of relationships are there in Laravel?

One To One (Polymorphic) One To Many (Polymorphic) Many To Many (Polymorphic)


1 Answers

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();
like image 74
Gayan Avatar answered Sep 27 '22 16:09

Gayan