laravel5.6基于子级过滤父行

disbfnqx  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(364)

我的数据库结构如下(我使用的是mysql):
产品:


# ------#---------#

| id   | int     |

# ------#---------#

| name | varchar |

# ------#---------#

产品特性:


# -------------#-----#

| product_id  | int |

# -------------#-----#

| property_id | int |

# -------------#-----#

属性:


# -------#---------#

| id    | int     |

# -------#---------#

| name  | varchar |

# -------#---------#

| value | varchar |

# -------#---------#

是否可以根据属性过滤产品对象?目前,我正在尝试使用如下方式:

$products = Product::with(['properties' => function($query){
    $query->where('name', 'testproperty');
}])
->get();

但是在运行这段代码时,elounk只对每个产品中找到的属性进行筛选,即使没有与我的where匹配的属性,仍然会找到所有产品。当我想显示我的所有属性时,还会雄辩地过滤我产品中的属性。
我目前的结果是:

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

有没有可能仅仅基于子对象(属性)过滤父类,而仍然获得与产品相关联的所有属性?

9lowa7mx

9lowa7mx1#

我想你需要 whereHas 检查子集合

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

相关问题