我在使用CakePHP创建了一个论坛,同时遵循教程并希望扩展它。
目前,在帖子中它允许我发表评论,但它们显示为最新 - >最古老的,所以它没有多大意义,我想扭转它。
这是我目前的关联,我对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);
}
}
答案 0 :(得分:2)
这样的事情应该这样做:
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
)
假设您在数据库表中有一个已创建的列。
编辑: 您可以在CakePHP文档http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html
中找到更多信息答案 1 :(得分:0)
避免使用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');
}