Question

I am trying to create a relationship between three models. My models are Roles, Responsibilities, and Employees. Conceptually, I believe i would set the relationships up like this:

Employee table:

id:int Pk

fName: varChar

lName: varChar

Role Table:

roldId: int pk

roleName: varChar

Responsibility Table:

reponsibilityId: PK int

responsibilityName: varChar

role_responsbility table:

role_responsibility_id: PK int

roleId: int FK

responsibilityId int FK

employee_role_responsibility Table:

id: int PK

role_responsibility_id int FK

employee_id: int FK

So, my question is, how do I model these relationships in my CakePHP model? This is what i have so far:

App::uses('AppModel', 'Model');
class Employee extends AppModel {
    public  $name = "Employee";
}

App::uses('AppModel', 'Model');
class Role extends AppModel {
    public  $name = "Role";

    public $hasAndBelongsToMany = array(
        'MemberOf' => array(
            'className' => 'Responsibility',
        )
    );
}

App::uses('AppModel', 'Model');
class Responsibility extends  AppModel {
    public  $name = "Responsibility";

    public $hasAndBelongsToMany = array(
        'MemberOf' => array(
            'className' => 'Role',
        )
    );
}

How do I join the roles_responsbility table with the employee table?

Thanks

Was it helpful?

Solution

I believe you're looking for HasMany Through [see it in the CakePHP book], which basically explains that you can add additional fields to your join table, create model for that join table, and associate it however you want.

So, in your responsibilities_roles table, you'd add an employee_id field.

Then, you make a model called RepsponsibilitiesRole and set it to belongsTo Employee.

You can literally think of it as model of it's own, because that's what it is - so you can make methods in it, or run finds through it...etc etc etc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top