yondaimehokage
yondaimehokage

Reputation: 253

CakePHP 3.x -> belongs to Many for theree tables

I have a setup where the relationship is three factors:

member group role

So a member may be part of multiple groups (and groups contain multiple members), but depending on that combination, the role will also differ.

A database person at work told me to set up the tables like this:

member
id name

group
id name

role
id name

member_group_role
id member_id group_id role_id

How do I get this to work with cakephp? I have successfully set up HABTM for only two linked tables but not three.

Thanks!

Upvotes: 1

Views: 220

Answers (1)

M Khalid Junaid
M Khalid Junaid

Reputation: 64476

According to your structure what i think there are 4 models one for each table. First 3 models will relates with 4th model as hasMany and 4th model will relate with these models as BelongsTo like

1) Member

class MemberTable extends Table
{
    public function initialize(array $config)
    {
        $this->hasMany('MemberHasGroupHasRole')
            ->setForeignKey('member_id');
    }
}

2) Group

class GroupTable extends Table
{
    public function initialize(array $config)
    {
        $this->hasMany('MemberHasGroupHasRole')
            ->setForeignKey('group_id');
    }
}

3) Role

class RoleTable extends Table
{
    public function initialize(array $config)
    {
        $this->hasMany('MemberHasGroupHasRole')
            ->setForeignKey('role_id');
    }
}

4) MemberHasGroupHasRole

class MemberHasGroupHasRoleTable extends Table
{
    public function initialize(array $config)
    {
        $this->belongsTo('Member')
            ->setForeignKey('member_id')
            ->setJoinType('INNER');

        $this->belongsTo('Group')
            ->setForeignKey('group_id')
            ->setJoinType('INNER');

        $this->belongsTo('Role')
            ->setForeignKey('role_id')
            ->setJoinType('INNER');
    }
} 

Upvotes: 1

Related Questions