CakePHP paginate and order by

后端 未结 4 746
南方客
南方客 2021-01-15 03:10

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:

相关标签:
4条回答
  • 2021-01-15 03:33

    try

    $all_threads = $this->Threads->find('all', 
                array(
                    'order' => 'Threads.created'
                )
            );
            $saida = $this->paginate($all_threads,[
                'conditions' => ['Threads.hidden' => 0]
            ]);
    
    0 讨论(0)
  • 2021-01-15 03:52

    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.

    0 讨论(0)
  • 2021-01-15 03:53

    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) 
    
    0 讨论(0)
  • 2021-01-15 03:55

    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.

    0 讨论(0)
提交回复
热议问题