简体   繁体   中英

CakePHP paginate and order by

It feels like I've tried everything so I now come to you.

I am trying to order my data but it isn't going so well, kinda new to Cake.

This is my code:

$this->set('threads', $this->paginate('Thread', array(
        'Thread.hidden' => 0,
        'Thread.forum_category_id' => $id,
        'order' => array(
            'Thread.created' => 'desc'
        )
    )));

It generates an SQL error and this is the last and interesting part:

AND `Thread`.`forum_category_id` = 12 AND order = ('desc') ORDER BY `Thread`.`created` ASC LIMIT 25

How can I fix this? The field created obviously exists in the database. :/

You need to pass in the conditions key when using multiple filters (ie order, limit...). If you just specify conditions, you can pass it as second parameter directly.

This should do it:

$this->set('threads', $this->paginate('Thread', array(
        'conditions' => array(
            'Thread.hidden' => 0,
            'Thread.forum_category_id' => $id
        ),
        'order' => array(
            'Thread.created' => 'desc'
        )
    )));

or perhaps a little clearer:

$this->paginate['order'] = array('Thread.created' => 'desc');
$this->paginate['conditions'] = array('Thread.hidden' => 0, ...);
$this->paginate['limit'] = 10;
$this->set('threads', $this->paginate());

if you get an error, add public $paginate; to the top of your controller.

Try

$this->set('threads', $this->paginate('Thread', array(
        'Thread.hidden' => 0,
        'Thread.forum_category_id' => $id
    ),
    array(
        'Thread.created' => 'desc'
    )
));

I'm not a Cake master, just a guess.

EDIT. Yes, thats right. Cake manual excerpt:

Control which fields used for ordering ... $this->paginate('Post', array(), array('title', 'slug'));

So order is the third argument.

try

$all_threads = $this->Threads->find('all', 
            array(
                'order' => 'Threads.created'
            )
        );
        $saida = $this->paginate($all_threads,[
            'conditions' => ['Threads.hidden' => 0]
        ]);

There are a few things to take note of in paginate with order. For Cake 3.x, you need :

1) Ensure you have included the fields in 'sortWhitelist'

$this->paginate = [

        'sortWhitelist' => [
            'hidden', 'forum_category_id', 
        ],


    ];

2) for 'order', if you put it under $this->paginate, you will not be able to sort that field in the view. So it is better to put the 'order' in the query (sadly this wasn't stated in the docs)

$query = $this->Thread->find()
->where( ['Thread.hidden' => 0, 'Thread.forum_category_id' => $id, ] )
->order( ['Thread.created' => 'desc'] );

$this->set('threads', $this->paginate($query) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM