dsxay48646 2017-03-01 17:01
浏览 16
已采纳

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

I want to modify an object before getting paginated and displayed in a JSON response, right now my code looks like this :

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

getPaginationConditions() looks like this

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

This returns :

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

I want to access each object following my conditions before the pagination and adding a "user" field, I know how to find my user, but I don't know how to access the objects that will get selected by the pagination conditions. It will look like :

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

Thanks for helping !

  • 写回答

1条回答 默认 最新

  • douyou1937 2017-03-01 17:12
    关注

    You could add 'contain' index on $this->paginate passing the model relationship that you want to add.

    <?php 
        $this->paginate = [ 
            'conditions' => $this->getPaginationConditions(),
            'contain' => ['User']
        ]; 
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何实验stm32主通道和互补通道独立输出
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题