Eager load relationships in laravel with conditions on the relation(laravel 中的急切加载关系,并带有关系条件)
问题描述
我在树中有相互关联的类别.每个类别 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 中的急切加载关系,并带有关系条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:laravel 中的急切加载关系,并带有关系条件
基础教程推荐
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何替换eregi() 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
