dsgwii4867 2017-02-28 18:45
浏览 19
已采纳

查询字符串的不同分页条件[CakePHP 3]

The user has to pass in the URL a query string which will return different pagination, if he entered none, one or both queries, the result will change. The code below works in CakePHP, but it looks horrible, is there a better way to achieve what I'm trying to do without those if, else if conditions?

if($this->request->query('date')) 
{ 
    $this->paginate = [ 
        'conditions' => [ 
          'Reservations.id_venue' => $this->Auth->user('id_venue_manager'), 
          'Reservations.date' => $this->request->query('date'), 
        ], 
    ]; 
} 
else if($this->request->query('id_user')) 
{ 
    $this->paginate = [ 
       'conditions' => [ 
          'Reservations.id_venue' => $this->Auth->user('id_venue_manager'), 
          'Reservations.id_user' => $this->request->query('id_user'), 
        ], 
    ]; 
} 
else if($this->request->query('id_user') && $this->request->query('date')) 
{ 
    $this->paginate = [ 
       'conditions' => [ 
          'Reservations.id_venue' => $this->Auth->user('id_venue_manager'), 
          'Reservations.id_user' => $this->request->query('id_user'), 
          'Reservations.date' => $this->request->query('date'), 
       ], 
    ]; 
} 
else 
{ 
    $this->paginate = [ 
       'conditions' => [ 
          'Reservations.id_venue' => $this->Auth->user('id_venue_manager'), 
       ], 
   ]; 
}
  • 写回答

1条回答 默认 最新

  • duanci9305 2017-02-28 18:56
    关注

    Try this

    <?php
    
    public function someMethod() {
         $this->paginate = [ 
           'conditions' => $this->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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?