Laravel 5.6根据子项筛选父行

时间:2018-05-09 10:31:05

标签: php mysql laravel eloquent laravel-5.6

我的数据库结构看起来像这样(我正在使用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();

但是,在运行此代码时,只会对每个产品中的属性进行过滤,即使没有属性与我的位置相匹配,仍会查找所有产品。当我想展示我的所有属性时,雄辩也会过滤我产品中的属性。

我目前的结果是这样的:

{
    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"
        }
    ]
    }
}

是否可以根据子对象(属性)过滤父类,并且仍然可以获得与产品关联的所有属性?

1 个答案:

答案 0 :(得分:2)

我猜您需要whereHas来检查子集合

$product = Product::with('properties')
                  ->whereHas('properties', function ($query) {
                       $query->where('name', '=', 'testproperty');
                 })->where('id', $id)->first();