2
votes

I'm having problems with a very simple ordering query. I have a Post model and a Tag model with a HABTM relationship and am trying to return a list of all posts with a particular tag assigned to them, ordered by the date the post is created.

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

While this returns the list of posts, it is not sorted by date.

With debugging on, it looks like the following query is being used:

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`)

Code for posts model:

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

Code for tags model:

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

Any help on the issue would be much appreciated - I'm using CakePHP 2.1. if it makes any difference.

3
Hi Abid, I've reviewed the HABTM page on the CakePHP site but don't see any reference to ordering of a results using conditions like this - please could you point out the relevant area relating to my query.Loftx
Just to be sure: did you state That the Tag model $actsAs containable?Bart Gloudemans

3 Answers

3
votes

What about defining the order attribute in your Tag Model?
Like e.g.

var $hasAndBelongsToMany = array(
    'Post' => array(
        'order' => 'Post.created_date'
    )
);
1
votes

I don't think that the "order" should be inside of "contain". Try with:

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

or just:

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

Read this:-

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

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

//try this

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'));
}