2017-03-01 30 views
0

我想获得分页和JSON响应显示之前修改对象,现在我的代码如下所示:访问每个对象和分页添加信息[CakePHP的3]

$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, 
    }, 
    [...] 

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

{ 
    "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", 
     [...] 
     } 
    }, 
    [...] 

感谢您的帮助!

+0

看来你没有关注的CakePHP [命名转换(https://book.cakephp.org/3.0/en/intro/conventions.html),你应该遵循CakePHP的命名转换。这将有助于提高生产力 – tarikul05

回答

0

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

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

在调整了我的关联后,我设法完成了这项工作,谢谢! –

相关问题