gpt4 book ai didi

Laravel5 ORM : how to alias multiple withCount on the same related object

转载 作者:行者123 更新时间:2023-12-03 15:06:57 34 4
gpt4 key购买 nike

我有一个 酒店模型有很多 客房可以是 已占用 .我应该如何查询:

酒店列表

  • 房间数
  • 占用房间数

  • 查询:
    $hotels = Hotel::where('foo',$bar)
    ->withCount('rooms')
    ->withCount(['rooms' => function ($query) {
    $query->where('status', 'Occupied');
    }])
    ->get();

    结果 :
    $hotel->rooms_count给出被占用房间的数量,这是最后一个 withCount表达。

    我想得到什么
  • $hotel->rooms_count作为每家酒店的房间数
  • $hotel->occupied_rooms_count作为每家酒店的入住房间数

  • 作为第二个 withcount 的别名:

    问题

    有没有办法到 别名 第二个 withCount在房间?

    最佳答案

    虽然@jaysingkar 的回答是一个很好的方法并且很好地回答了这个问题,是的,可以为 withCount() 取别名。尽管尚未记录在案,但请调用:

    $hotels = Hotel::where('foo', $bar)
    ->withCount([
    'rooms',
    'rooms AS occupied_rooms' => function ($query) {
    $query->where('status', 'Occupied');
    }
    ])
    ->get();

    这将为您提供 $hotel->occupied_rooms_count与每家酒店的入住房间数。 :)

    发生这种魔法的代码 can be seen here .它是通过 PR #15279 在 Laravel 5.3.7 中添加的.

    更新:我已经提交了 PR,现在是 properly documented . :)

    关于Laravel5 ORM : how to alias multiple withCount on the same related object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39384676/

    34 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com