Thursday, January 08, 2009

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

Monday, January 05, 2009

Comments

Dear readers!

Blogspot have too non-usability UI for comment reading and answering.

Yes. I read all your comments, but I remember - I saw some questions in your comments, but after "aprove" I cann't found comments ;-(

If you have question - ask me in twitter: cakephp
http://twitter.com/cakephp

I'll try answer to all your question with my bad english ;-)

Labels: ,