PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, February 22, 2022

[FIXED] CakePHP 3 Paginator using FIELD() in ORDER clause

 February 22, 2022     cakephp, cakephp-3.0, mysql, pagination     No comments   

Issue

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


Answered By - arilia
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing