【发布时间】:2018-05-09 18:42:19
【问题描述】:
我的数据库结构如下(我使用的是 MySQL):
产品:
#------#---------#
| id | int |
#------#---------#
| name | varchar |
#------#---------#
products_properties:
#-------------#-----#
| product_id | int |
#-------------#-----#
| property_id | int |
#-------------#-----#
属性:
#-------#---------#
| id | int |
#-------#---------#
| name | varchar |
#-------#---------#
| value | varchar |
#-------#---------#
是否可以根据属性过滤产品对象?在我尝试像这样使用急切加载:
$products = Product::with(['properties' => function($query){
$query->where('name', 'testproperty');
}])
->get();
但是,当运行此代码时,eloquent 仅过滤在每个产品中找到的属性,即使没有与我的位置匹配的属性,仍然会找到所有产品。当我想显示我的所有属性时,eloquent 还会过滤我产品中的属性。
我现在的结果是这样的:
{
id: 1,
name: "test",
properties: [
{
id: 1,
name: "testproperty",
value: "testvalue"
}
]
},
{
id: 2,
name: "test2",
properties: [
]
}
但我正在寻找这样的东西:
{
id: 1,
name: "test",
properties: [
{
id: 1,
name: "testproperty",
value: "testvalue"
},
{
id: 2,
name: "testproperty2",
value: "testvalue2"
}
]
}
}
是否可以仅根据子对象(属性)过滤父类并仍然获取与产品关联的所有属性?
【问题讨论】:
标签: php mysql laravel eloquent laravel-5.6