【问题标题】:Laravel 5.6 filter parent rows based on childrenLaravel 5.6 根据子级过滤父行
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

    • 非常感谢我正在寻找的东西!
    猜你喜欢
    • 2015-03-19
    • 2018-04-11
    • 2016-12-22
    • 1970-01-01
    • 2020-01-14
    • 2018-10-10
    • 1970-01-01
    • 2019-03-06
    • 1970-01-01
    相关资源
    最近更新 更多