2

我遇到了一个非常简单的订购查询的问题。我有一个Post模型和一个Tag具有 HABTM 关系的模型,并且正在尝试返回所有帖子的列表,这些帖子具有分配给它们的特定标签,按帖子创建日期排序。

$this->set('data', $this->Post->Tag->find('all', array(
    'conditions' => array('Tag.id' => 1),
    'contain' => array('Post' => array(
        'order' => 'Post.created_date desc'
    ))
)));

虽然这会返回帖子列表,但它不是按日期排序的。

启用调试后,似乎正在使用以下查询:

SELECT `Post`.`id`, `Post`.`title`, `Post`.`created_date`, `PostsTag`.`post_id`, `PostsTag`.`tag_id`
FROM `database`.`posts` AS `Post`
JOIN `database`.`posts_tags` AS `PostsTag` ON (`PotsTag`.`tag_id` = 1 AND `PostsTag`.`post_id` = `Post`.`id`)

帖子模型的代码:

class Post extends AppModel {
    public $name = 'Post';
    public $hasAndBelongsToMany = array('Tag');
}

标签模型的代码:

class Tag extends AppModel {
    public $name = 'Tag';
    public $hasAndBelongsToMany = array('Post');
}

对此问题的任何帮助将不胜感激 - 我使用的是 CakePHP 2.1。如果它有什么不同。

4

3 回答 3

3

在标签模型中定义 order 属性怎么样?
像例如

var $hasAndBelongsToMany = array(
    'Post' => array(
        'order' => 'Post.created_date'
    )
);
于 2012-07-28T22:19:00.473 回答
1

我认为“订单”不应该在“包含”之内。尝试:

$this->set('data', $this->Post->Tag->find('all', array(
    'conditions' => array('Tag.id' => 1),
    'contain' => array('Post'),
    'order' => 'Post.created_date desc'
)));

要不就:

 $this->set('data', $this->Post->Tag->find('all', array(
        'conditions' => array('Tag.id' => 1),
        'order' => 'Post.created_date desc'
 )));
于 2012-07-24T21:09:39.373 回答
0

读这个:-

http://www.jamesfairhurst.co.uk/posts/view/adding_tags_to_a_cakephp_app_hasAndBelongsToMany/

http://edivad.wordpress.com/2007/04/19/cakephp-hasandbelongstomany-habtm/

//尝试这个

CREATE TABLE `tags` (
  `id` int(11) NOT NULL auto_increment,
  `tag` varchar(100) NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  PRIMARY KEY  (`id`)
);


CREATE TABLE `posts_tags` (
  `post_id` int(11) NOT NULL,
  `tag_id` int(11) NOT NULL
);


//Creating the Models and Relationships

class Tag extends AppModel {
    var $name = 'Tag';
    var $hasAndBelongsToMany = array('Post'=>array('className'=>'Post'));
}

class Post extends AppModel {
    var $name = 'Post';
    var $hasMany = array('Comment'=>array('className'=>'Comment'));
    var $hasAndBelongsToMany = array('Tag'=>array('className'=>'Tag'));
}
于 2012-07-28T21:59:40.943 回答