【问题标题】:Access each object and add informations in pagination [CakePHP 3]访问每个对象并在分页中添加信息 [CakePHP 3]
【发布时间】:2017-03-02 01:12:48
【问题描述】:

我想在分页并在 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,
    },
    [...]

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

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

感谢您的帮助!

【问题讨论】:

  • 看来你没有关注 CakePHP Naming Conversion 你应该关注 CakePHP 命名转换。这将有助于提高生产力

标签: php json cakephp pagination cakephp-3.0


【解决方案1】:

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

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

【讨论】:

  • 在调整了我的关联后,我设法完成了这项工作,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-04
  • 1970-01-01
  • 2021-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多