访问每个对象并在分页中添加信息[CakePHP 3]

时间:2017-03-01 17:01:45

标签: php json cakephp pagination cakephp-3.0

我想在获得分页并在JSON响应中显示之前修改对象,现在我的代码如下所示:

$this->paginate = [ 
    'conditions' => $this->getPaginationConditions(),
    ]; 
$this->set('reservations', $this->paginate($this->Reservations));
$this->set('_serialize', ['reservations']);

getPaginationConditions()看起来像这样

private function getPaginationConditions()
{
    $conditions = ['Reservations.id_venue' => $this->Auth->user('id_venue_manager')];  
    if ($date = $this->request->query('date')) {
        $conditions['Reservations.date'] = $date;
    }
    if ($user = $this->request->query('id_user')) {
        $conditions['Reservations.id_user'] = $user;
    }
    return $conditions;
}

返回:

 {
  "reservations": [
    {
      "id_reservation": 139,
      "reservation_type": "",
      "date": "2017-09-04T00:00:00",
      "time": "2017-03-01T10:00:00",
      "id_venue": 1,
      "id_user": 149,
    },
    {
      "id_reservation": 140,
      "reservation_type": "",
      "date": "2017-09-04T00:00:00",
      "time": "2017-03-01T20:00:00",
      "id_venue": 1,
      "id_user": 149,
    },
    [...]

我希望在分页之前按照我的条件访问每个对象并添加“user”字段,我知道如何找到我的用户,但我不知道如何访问将通过分页条件选择的对象。它看起来像:

 {
  "reservations": [
    {
      "id_reservation": 139,
      "reservation_type": "",
      "date": "2017-09-04T00:00:00",
      "time": "2017-03-01T10:00:00",
      "id_venue": 1,
      "id_user": 149,
      "user" : {
         "firstname" : "test",
         "lastname" : "test",
         "id_user" : "149",
         [...]
      }
    },
    {
      "id_reservation": 140,
      "reservation_type": "",
      "date": "2017-09-04T00:00:00",
      "time": "2017-03-01T20:00:00",
      "id_venue": 1,
      "id_user": 149,
      "user" : {
         "firstname" : "test",
         "lastname" : "test",
         "id_user" : "149",
         [...]
      }
    },
    [...]

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您可以在'contain'上添加$this->paginate索引,并传递您要添加的模型关系。

<?php 
    $this->paginate = [ 
        'conditions' => $this->getPaginationConditions(),
        'contain' => ['User']
    ]; 
?>