Search code examples
phpmysqlcakephppaginationcakephp-3.0

CakePHP 3 Paginator using FIELD() in ORDER clause


I have a question regarding the Paginator Component of CakePHP3 (3.0.13). I'm using the MYSQL function FIELD() to order my data, like that:

$this->paginate = array_merge_recursive([
      'conditions' => [
           'zip IN' => $zips
      ],
           'order' => [
                  'FIELD(zip, '.rtrim(implode(',', $zips), ',').')',
                  'ispro' => 'desc',
           ],
           $this->paginate
     ]); 

When I apply this to my $this->paginate() it wouldn't be recognized as long as the query param sort is set. To avoid this I remove the sort in my request with:

if (isset($this->request->query['sort'])) {
      unset($this->request->query['sort']);
}

This is working, but I was wondering if there is a better solution, maybe in the paginator component itself, which I haven't found yet.


Solution

  • you can sort your query before you paginate it. Your sort conditions will come before the one appended from the paginator component

    so you can do

    $dentists = $this->Dentists->find()
        ->order([
            'FIELD(zip, '.rtrim(implode(',', $zips), ',').')',
            'ispro' => 'desc'
         ]);
    
    $this->paginate = array_merge_recursive([
        'conditions' => [
            'zip IN' => $zips
        ],
        $this->paginate
     ]); 
    
    $dentists = $this->paginate($dentists);