Eager load relationships in laravel with conditions on the relation

点点圈 提交于 2021-02-04 13:31:09

问题


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();

回答1:


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();



回答2:


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();


来源:https://stackoverflow.com/questions/41679771/eager-load-relationships-in-laravel-with-conditions-on-the-relation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!