James Dawson
James Dawson

Reputation: 5409

Ordering posts by their tag in a HABTM relationship

I have correctly set up a HABTM relationship between Post and Tag. When the user navigates to a URL like http://site.com/tag/test I want to show all the posts tagged with test.

Using the following code gets the tag information and all the posts which have that tag:

public function view($name) {
    $this->set('tag', $this->Tag->findByName($name));
}

However, the posts it returns are not sorted by their created column, they seem to be retrieved on a "first come first serve" basis. I tried doing this:

public function view($name) {
    $this->set('tag', $this->Tag->findByName($name, array(
        'order' => array('Post.created DESC')
    )));
}

However that gave me an SQL error:

Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Tag.' in 'field list'

SQL Query: SELECT DISTINCT Tag.` FROMportfolio.tagsASTag WHERETag.name` = 'test' LIMIT 1

Is there any way for me to order posts from newest to oldest in the query or do I have to reformat the result array in my controller?

Upvotes: 1

Views: 89

Answers (1)

tigrang
tigrang

Reputation: 6767

You need to do a find on the Post model and then force an ad-hoc join from the join table to the tag table, set a condition where Tag.name = $name and sort Post.created DESC

Or by rebinding some models. Example from cookbook:

$this->Recipe->bindModel(array(
    'hasOne' => array(
        'RecipesTag',
        'FilterTag' => array(
            'className' => 'Tag',
            'foreignKey' => false,
            'conditions' => array('FilterTag.id = RecipesTag.tag_id')
))));
$this->Recipe->find('all', array(
        'fields' => array('Recipe.*'),
        'conditions'=>array('FilterTag.name'=>'Dessert')
));

Apply it to your case (Recipe - > Post and RecipesTag -> PostsTag) and just add your sort

Upvotes: 0

Related Questions