我遇到一个非常简单的订购查询问题。我有一个Post
模型和一个带有HABTM关系的Tag
模型,我正在尝试返回所有帖子的列表,其中包含分配给它们的特定标记,按帖子创建日期排序。
$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。如果它有任何区别。
答案 0 :(得分:3)
如何在标签模型中定义订单属性? 比如说。
var $hasAndBelongsToMany = array(
'Post' => array(
'order' => 'Post.created_date'
)
);
答案 1 :(得分: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'
)));
答案 2 :(得分: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'));
}