Laravel Eloquent to join table and count related

2020-02-11 06:00发布

问题:

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?

回答1:

$this->model->leftJoin('Rooms', 'Properties.ID', '=', 'Rooms.Property')
  ->selectRaw('Properties.*, count(Rooms.RoomID) as RoomsCount')
  ->groupBy('Properties.ID')
  ->get();


回答2:

Define the relationship on your Property model class:

<?php 

namespace App\Models;

class Property extends Model {
  public function rooms() {
    return $this->hasMany(Room::class);
  }
}

$properties = Property::withCount(['rooms'])->get();

This will add a rooms_count to the result.