Home » Php » php – Eager load relationships in laravel with conditions on the relation

php – Eager load relationships in laravel with conditions on the relation

Posted by: admin July 12, 2020 Leave a comment

Questions:

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();
How to&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();

Answer:

You can use whereHas to limit your results based on the existence of a relationship as:

ProductCategory::with('children')
            ->with(['products' => function ($q) use($SpecificID) {
                $q->whereHas('types', function($q) use($SpecificID) {
                    $q->where('types.id', $SpecificID)
                });
            }])
            ->get();