Laravel Eloquent to join table and count related

前端 未结 2 1994
遇见更好的自我
遇见更好的自我 2020-12-06 12:06

How do I use join with Eloquent taking in consideration the following table structure:

I have a properies table

---------------------
ID    | Name 
-         


        
2条回答
  •  无人及你
    2020-12-06 12:48

    This is more of a MySQL join+group+select trick which includes following steps.

    1. Join your relation table(use join if you want to exclude rows with RoomsCount=0, else use leftJoin)
    2. Use groupBy by primaryKey to avoid duplicates of the join.
    3. Select count of joined table
        $this->model->leftJoin('Rooms', 'Properties.ID', '=', 'Rooms.Property')
          ->selectRaw('Properties.*, count(Rooms.RoomID) as RoomsCount')
          ->groupBy('Properties.ID')
          ->get();
    

提交回复
热议问题