更改从 CakePHP 中的数据库检索的订单项目?

Changing the order items are retrieved from the DB in CakePHP?

我在学习教程的同时使用 CakePHP 创建了一个论坛,并希望扩展它。

目前,在 post 中,它允许我发表评论,但它们显示为最新 -> 最旧,因此没有多大意义,我想撤消此操作。

这是我目前的协会,我对 PHP/Cake 还很陌生,所以我不确定从这里该往哪里走,非常感谢任何帮助!

public $hasMany = array(
        'Post' => array(
            'className' => 'Post',
            'foreignKey' => 'forum_id',
            'dependent' => false,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        )

对于那些询问这是我控制器中的功能的人:

public function add($topicId=null) {
        if ($this->request->is('post')) {
            $this->request->data['Post']['user_id'] = $this->Auth->user('id');

            if ($this->Post->save($this->request->data)) {
                $this->Session->setFlash(__('Post has been created'));
                $this->redirect(array('controller'=>'topics','action'=>'view',$this->request->data['Post']['topic_id']));
            }

        } else {
            if (!$this->Post->Topic->exists($topicId)) {
                throw new NotFoundException(__('Invalid topic'));
            }

            $this->Post->Topic->recursive = -1;
            $topic = $this->Post->Topic->read(null,$topicId);

            $this->Post->Forum->recursive = -1;
            $forum = $this->Post->Forum->read(null,$topic['Topic']['forum_id']);

            $this->set('topic',$topic);
            $this->set('forum',$forum);
        }
    }

应该这样做:

public $hasMany = array(
    'Post' => array(
        'className' => 'Post',
        'foreignKey' => 'forum_id',
        'dependent' => false,
        'order' => 'Post.created ASC' //order the Posts in ascending order based on whe they were created
    )

假设您在数据库中创建了一个列table。

编辑: 您可以在 CakePHP 文档中找到更多信息 http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html

避免使用read(),最好使用find('first')。所以你可以像这样重写你的查询:-

$this->Post->Topic->find('first', array(
    'contain' => array(
        'Post' => array(
            'order' => array(
                'Post.created' => 'asc',
                'Post.id' => 'asc'
            )
        )
    )
));

order 传递一个数组而不是字符串允许您按多个条件排序。上面的示例将创建以下 ORDER SQL:-

ORDER BY Post.created ASC, Post.id ASC

您还可以在模型本身上定义默认顺序,这非常有用:-

class Post extends AppModel {

    public $order = array('Post.created' => 'asc', 'Post.id' => 'asc');

}