Derek J
Derek J

Reputation: 807

How to define many-to-many relationship in CakePHP

I have an app in which Users belong to many Categories. So I have a Users table, Categories and Users2Categories table. The Users2Categories table consists of a user_id and category_id. So I guess the question is: do I create a model for Users2Categories? Ultimately, I would like to be able to "find" User objects and have their respective categories attached.

Also, can I define this relationship via the baking console?

Upvotes: 1

Views: 8355

Answers (3)

bancer
bancer

Reputation: 7525

  1. Read about HABTM in the cookbook. Rename 'Users2Categories' table to 'categories_users'.
  2. You can bake the models from the console but you must have the correct tables first (see above).

Upvotes: 8

Rob Wilkerson
Rob Wilkerson

Reputation: 41256

So, you asked two questions and got some good information, but the answers are pretty straightforward:

do I create a model for Users2Categories?

You can, but I wouldn't. Cake will create a model for the join at runtime. Since this model/table exists solely to facilitate the join (i.e. it has no properties or methods of its own), just let Cake do that work for you. As stated by @bancer, though, you will need to name the table according to Cake's convention.

Also, can I define this relationship via the baking console?

No. You can create the model skeleton, but that won't include the definition of any associations. AFAIK, there's no way to do that. Bake the skeleton, flesh it out with associations, etc.

I could not have been more wrong. See comments. Thanks for the education, @bancer and @beporter.

Upvotes: 0

Leo
Leo

Reputation: 6571

HABTM is definitely the way to go.

Cake will handle the join table for you, provided you adhere to the Cake conventions.

Read the section in the Book linked to by bancer, then read it again. Then read this: http://mrphp.com.au/code/working-habtm-form-data-cakephp which will help you with realworld implementation.

Upvotes: 1

Related Questions