CakePHP paginate and order by

2020-03-30 01:00发布

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. :/

标签: php cakephp
4条回答
闹够了就滚
2楼-- · 2020-03-30 01:39

You need to pass in the conditions key when using multiple filters (i.e. 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.

查看更多
Viruses.
3楼-- · 2020-03-30 01:47

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.

查看更多
Lonely孤独者°
4楼-- · 2020-03-30 01:50

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) 
查看更多
小情绪 Triste *
5楼-- · 2020-03-30 02:02

try

$all_threads = $this->Threads->find('all', 
            array(
                'order' => 'Threads.created'
            )
        );
        $saida = $this->paginate($all_threads,[
            'conditions' => ['Threads.hidden' => 0]
        ]);
查看更多
登录 后发表回答