Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

I have a properies table

---------------------
ID    | Name 
---------------------
1     | Property Name

than I have rooms

----------------------
RoomID | Property
----------------------
A-212  | 1
---------------------- 
F-1231 | 1

here Property is the foreign key than I want to get all Properties and count how many rooms do they have each

The query which retrives all looks like

   class PropertiesRepository extends EloquentBaseRepository implements PropertiesInterface
{

    use TaggableRepository;

    /**
     * Construct 
     * @param Properties $properties 
     */
    public function __construct( Properties $properties )
    {
        $this->model = $properties;
    }
     /**
     * Get all properties joining rooms
     * @return Properties
     */
    public function getAll()
    {
        return $this->model->get();
    }
}

How do I extend this query to get the desired result?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
423 views
Welcome To Ask or Share your Answers For Others

1 Answer

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...