Thursday, January 08, 2009

double HABTM how to?

We have:

Post HABTM Tag
Post HABTM Category

We need:

Get all posts where = M, = N
In CakePHP style, of couse ;-)

Scaffolding (just use cake console, nothing strange, all - typical).


posts: id, title, body
tags: id, title
category: id,title

join tables:

posts_tags: id, post_id, tag_id
categories_tags: id, post_id, category_id

How to?


$this->Post->bindModel(array('hasOne' => array('PostsTag','CategoriesPost')));

(add param false if want to make paginate ;-)

And now:

$posts = $this->Post->find('all',array(
'fields' => 'Post.*',
'conditions' => array('PostsTag.tag_id' => 1,'CategoriesPost.category_id' => 4),

That's all, folks.

You can add params recursive = 0 (I think it good idea to reduce data in result)
You can use any cake-style 'or', 'and' in conditions query.

And this works well ;-)

Labels: , ,


Post a Comment

Subscribe to Post Comments [Atom]

<< Home