Friday, 2 September 2011

Cake PHP useful tips: double HABTM how to?

We have:

Post HABTM Tag
Post HABTM Category

We need:

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

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

Table:

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?

Easy...

$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: , ,

No comments:

Post a Comment