Laravel Eloquent加入表和计数相关

时间:2014-07-09 08:15:15

标签: sql join laravel-4 eloquent

如何在考虑下表结构的情况下使用与Eloquent的连接:

我有一张特色表

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

比我有房间

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

此处属性是外键 比我想获得所有属性并计算每个属性有多少个房间

重审所有的查询看起来像

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

如何扩展此查询以获得所需的结果?

2 个答案:

答案 0 :(得分:16)

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

答案 1 :(得分:3)

在Property模型类上定义关系:

<?php 

namespace App\Models;

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

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

这将在结果中添加一个rooms_count。