I apologize in advance... I'm a complete noob to cakephp. As such, I'm having great difficulty in getting my models related correctly. To be more specific, I'm having the most trouble with the "hasMany Through" relationship. I've been beating my head against the wall, and scouring the cookbook, but haven't found it as clear as i had hoped.
I'm currently writing a web app with many complex relationships. I'll start with stripped down versions of my tables.
- Users:
- id, name
- Groups:
- id, name, department_id
- Departments:
- id, name, district_id
- Districts:
- id, name
- Roles
- id, name
- Note that roles are what I call my levels of access(user, admin, superuser).
- groups_users -group_id, user_id
- departments_users:
- department_id, user_id, role_id
RELATIONSHIPS:
- User hasAndBelongsToMany Department
- Department hasAndBelongsToMany User
- User hasAndBelongsToMany Group
- Group hasAndBelongsToMany User
- Department hasMany Group
- Group belongsTo Department
- District hasMany Department
- Department belongsTo District
Now, here's where i get a bit more confused. Since users can be in multiple departments, in multiple districts, as well as have varying roles within each department (e.g. Department admin in DEPT A of DISTRICT A, and District Admin in DEPT B in DISTRICT B), I chose to place the user's level of access in the departments_users table. Since I'm storing more than foreign keys for the named models, ie role_id, this seems like a candidate for the hasMany through relationship, but cake's docs also mention a keepExisting option for the model relationship.
so i tried this, using the example from the cake site. leaving all of the initial datatables and relationships in place, I added a DepartmentPosition model and controller, like the following:
user.php
public $hasMany = array('DepartmentPosition');
department.php
public $hasMany = array('DepartmentPosition');
department_position.php
public $belongsTo = array('User','Department');
I also added a new data table:
- department_position:
- id, department_id, user_id, role_id
OK, so what i got, likely mistakenly from the cake docs, is that when I add a user to a department, i can include a role_id, and that will all be saved in the department_position data table, if I do saveAll().
I'm not sure if that is at all the right thing to do. I feel more confused now, having written this out, than i did before. lol. I'm very confused as to how to get these relationships correctly set-up. And, still, once I do, I feel i'll have trouble accessing data from associated models. I'm getting errors galore and am unable to retrieve much associated model data. eek. like I said, i'm not the strongest cake person.
Any suggestions, before i have an aneurysm?! lol. Thanks loads. Any help will be a lot of help!