How to self join a many to many table in cakephp 3?

1k views Asked by At

I try to self join my table user to get parent-child associations but it didn't work

here is my association in the Users model:

        $this->belongsToMany('Parents', [
            'className' => 'Users',
            'joinTable' => 'users_users',
            'foreignKey' => 'id',
            'targetForeignKey' => 'parent_id'
            ]);
        $this->belongsToMany('Childs', [
            'className' => 'Users',
            'joinTable' => 'users_users',
            'foreignKey' => 'id',
            'targetForeignKey' => 'child_id'
            ]);

I didn't make parameters in the UsersUsers model.

When I do:

  $test = $this->Users->find()->where(['id =' => 65])->contain(['Parents']);

I get the child entity but the parents property is empty so I do something wrong but I don't know what.

Thanks for your help :)

1

There are 1 answers

0
Chuug On BEST ANSWER

My foreignKeys were bad, that was like this:

    $this->belongsToMany('Parents', [
        'className' => 'Users',
        'joinTable' => 'users_users',
        'foreignKey' => 'child_id',
        'targetForeignKey' => 'parent_id'
        ]);
    $this->belongsToMany('Childs', [
        'className' => 'Users',
        'joinTable' => 'users_users',
        'foreignKey' => 'parent_id',
        'targetForeignKey' => 'child_id'
        ]);

Problem solved