如何在CakePHP3中正确使用分组依据

时间:2018-09-05 16:08:42

标签: cakephp group-by cakephp-3.0 query-builder

我想基于模型预留字段Reservation.people(int)计算一个房间中的人数。

错误:

  

预订未与组关联

我在做什么错了?

$hostel = $this->Hostel->get($id, [
    'contain' => [
        'Room' => [
            'conditions' => [
                'Room.status' => '0'
            ],
            'sort' => [
                'Room.number'
            ],
            'Reservation' => [
                'fields' => [
                    'reservation_room_id' => 'Reservation.room_id',
                    'sum' => 'SUM(Reservation.people)'
                ],
                'conditions' => [
                    'Reservation.status' => '0'
                ],
                'group' => [
                    'Reservation.room_id'
                ]
            ]
        ]
    ]
]);

1 个答案:

答案 0 :(得分:-1)

由于没有在模型中定义关联,因此出现此错误。

Cakephp 2.x

假设预订与组之间有多对一的关系,那么您可以在下面的文件中定义您的关联,如下所示

  

app / Model Reservation.php

class Reservation extends AppModel {
    public $belongsTo = 'Group';

}

Cakephp 3.x

  

/src/Model/Table/ReservationsTable.php

class ReservationsTable extends Table
{
    public function initialize(array $config)
    {
        $this->belongsTo('Groups');
    }
}

希望这会有所帮助!