問題描述
我在樹中有相互關聯的類別.每個類別 hasMany
子項.每個終端類別有許多
個產品.
I have categories related to each other in a tree. Each category hasMany
children. Each end category hasMany
products.
產品也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');
}
產品型號
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();
推薦答案
代替當前查詢,嘗試這是否符合您的需要.(我根據您的評論修改了我的答案如下)
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();
這篇關于laravel 中的急切加載關系,并帶有關系條件的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!