views:

32

answers:

1

Hi All,

I am confused about how to set this up using Cake's conventions. I have a table of users (pretty standard: id (pk, auto-increment), username, password), a table of groups (also pretty standard: id, name, user_id) and a practice table (like a doctor's practice, not like "practice makes perfect"). The practice table will be owned by one user (that belongs to a dr group) and will zero or more other users that belong to the practice (and are standard members).

here's a very rough drawing of what I am thinking:

user ---(belongs to)---> group
  |
  |
  +<----(belongs to)---- practice
  |                        ^
  |                        |
  +-------------------(belongs to)

I understand how to make sure that only members of group "caretaker" can own a practice and I know how to make sure that each user has one group and all of that.

Normally I would understand how to make "practice has many user" and "practice belongs to user". Where I'm getting stumped, though, is how do I specify that a practice "has one" user but also "has many" users. This is because the practice doesn't know the groups that a user belongs to in Cake. And (to my knowledge), I can't just say "practice.owner_id is a foreign key that matches user.id" because Cake won't understand this.

If I am mistaken, can you please provide an explanation/link to a doc to help me on my way? Thanks SO.

+1  A: 

I can't just say "practice.owner_id is a foreign key that matches user.id" because Cake won't understand this.

Well, you can... just not the way you are thinking.

You set up a belongsTo on your Practice model... your user_id field in the Practice will be the owner. Then, set up another belongsTo on your User model with a practice_id field. If you want, you can even set up a hasMany on the practice to tie it to the user. Just name the belongsTo and hasMany associations differently. Call the Practice belongsTo User relationship Owner in your model. Then, when you actually pull records out of the database, you'll get an Owner array and a User array on you Practice (assuming appropriate $recursive levels.)

Reading over that, that might be confusing... to sum up:

Associations in User:

  • belongsTo Practice

Associations in Practice:

  • hasMany User
  • belongsTo Owner (alias for User)
Finster
Thanks, that sounds like exactly what I need. Just one followup, when you say owner is an alias for user, do you mean that I should create a different database table or is the alias a Cake alias?
Tim
Sorry, yeah, that's kind of unclear...Basically, it's just going to be the name of the association in your Practice model. Then, in the association itself, you'll set the className for Owner to User.Here's a manual page on it: http://book.cakephp.org/view/1046/Multiple-relations-to-the-same-model
Finster
oooooh, I missed that doc. Thanks! I think I understand now.
Tim