【问题标题】:Nested search/filtering with Laravel/Eloquent使用 Laravel/Eloquent 进行嵌套搜索/过滤
【发布时间】:2020-04-18 06:07:57
【问题描述】:

假设我有一张房子的桌子,每个房子都有很多房间,每个房间里都有很多物品。每个项目都有一种颜色。

Houses
+ id
+ name

Rooms
+ id
+ house_id (FK house.id)
+ name

Items
+ id
+ room_id (FK room.id)
+ name
+ color

对应的模型关系($this->hasMany())已经建立。

然后我想返回一个嵌套的 JSON 对象,其中包含所有 red 项,房屋作为对象的顶层。也就是说,JSON 对象的结构是一个房屋列表,每个房屋都有一个房间列表,每个房间都有一个项目列表。

要明确:如果房子没有房间里有红色物品,我根本不希望房子在 JSON 对象中。如果它只有一些带有红色物品的房间,我只想要对象中的那些房间。最后,当然,对于里面有红色物品的房间,我只希望那些红色物品在对象中。

我怎样才能最好地使用 ->where() 之类的约束来做到这一点,或者如果不可能,我怎样才能最好地使用原始查询来做到这一点?

编辑: 我已经使用 whereHas 创建了一个嵌套查询,类似于:

House::whereHas('rooms', function ($rooms) {
    $rooms->whereHas('items', function ($items) {
        $items->where('color', 'red);
    });
});

虽然这只给了我其中有红色物品的房屋,但它也将这些房屋的非红色物品保留在对象中。

【问题讨论】:

  • whereHas() 方法此时是你的朋友。 Official doc
  • 嗯,看看我的编辑。我不确定如何将其扩展到所需的行为。

标签: sql database laravel eloquent


【解决方案1】:

要过滤掉没有红色的房间,我相信您可以使用with() 可选查询。

House::with(['rooms.items' => function($query) {
    $query->where('color', 'red');
}])->whereHas('rooms', function ($rooms) {
    $rooms->whereHas('items', function ($items) {
        $items->where('color', 'red);
    });
});

【讨论】:

    猜你喜欢
    • 2022-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 2014-09-18
    • 1970-01-01
    • 1970-01-01
    • 2021-11-19
    相关资源
    最近更新 更多