gpt4 book ai didi

php - Laravel 中的热切加载关系以及关系条件

转载 作者:行者123 更新时间:2023-12-02 04:33:23 26 4
gpt4 key购买 nike

我在树中具有彼此相关的类别。每个类别都有许多子类别。每个最终类别都有许多产品。

产品也belongsToMany不同的类型。

我想立即加载类别及其子项和产品,但我也想提出一个条件,即产品属于某种类型。

这就是我的类别模型的样子

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');
}

在我的数据库中,我有四个表:类别、产品、类型和产品类型

我已经尝试像这样进行急切加载,但它会加载所有产品,而不仅仅是满足条件的产品:

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

最佳答案

尝试这是否符合您的需求,而不是当前查询。(我根据您的评论修改了我的答案)

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

关于php - Laravel 中的热切加载关系以及关系条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41679771/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com