tags:

views:

31

answers:

3

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?

+4  A: 
  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).
bancer
+1 Yep - this is the way.
Leo
A: 

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.

Leo
A: 

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.

Rob Wilkerson
??? the baking (models) script asks for associations and in fact it bakes associations to the model file. Have I misunderstood you? What did you mean?
bancer
Nope, you sure didn't; I guess I'm completely wrong about that (he said with apologies for the misinformation). I swear I've never seen/noticed that before. If you're correct, then that's entirely my bad. Thanks for the education.
Rob Wilkerson
@bancer--what's the syntax for that? Granted, I don't bake often, but when I do a `./cake bake model MyModel`, I don't get prompted for associations. Are you referring to the "all" option that would presumably be used only once, before any models already exist?
Rob Wilkerson
@Rob: Just use `cake bake` by itself and then run through the interactive wizard. It'll do all of the heavy lifting for you.
beporter
@Rob: yeah, use `cake bake`.
bancer