laravel 中的急切加载关系,并带有关系条件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41679771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Eager load relationships in laravel with conditions on the relation
提问by Suemayah Eldursi
I have categories related to each other in a tree. Each category hasMany
children. Each end category hasMany
products.
我在树中有相互关联的类别。每个类别的hasMany
孩子。每个终端类hasMany
产品。
The products also belongsToMany
different types.
产品也belongsToMany
不同类型。
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
在我的数据库中,我有四个表:category、product、type 和 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();
回答by Gayan
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();
回答by Amit Gupta
You can use whereHas
to limit your results based on the existence of a relationship as:
您可以whereHas
根据以下关系的存在来限制结果:
ProductCategory::with('children')
->with(['products' => function ($q) use($SpecificID) {
$q->whereHas('types', function($q) use($SpecificID) {
$q->where('types.id', $SpecificID)
});
}])
->get();