laraveleloquent

How to alias multiple withCount on the same related object


I have a Hotel model which has Many Rooms that can be occupied. How should I query this:

Hotel list

The query:

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

The result:

$hotel->rooms_count gives the count of occupied rooms, which is the last withCount expression.

What I'm trying to get

as an alias of the second withcount:

Is there a way to alias the second withCount on Room?


Solution

  • Instead of specifying where clause in your withCount define the relation for occupied rooms in Hotel Model.

    public function occupied_rooms(){
        return $this->hasMany(Room::class)
                    ->where('status', 'Occupied');
    }
    

    Now, in your controller use, withCount('occupied_rooms').

    $hotels = Hotel::where('foo',$bar)
    ->withCount(['rooms','occupied_rooms'])
    ->get();