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 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口