0
votes

I am using CakePHP 3.x.
My question is : Is it possible to have many belongsTo() associations with the same foreign key ?

Here's my issue :
I have three fields in my table which are using the same foreign key.

In the Model Table, I used belongsTo() association this way :

$this->belongsTo('Pilotes', [
    'className' => 'Users',
    'foreignKey' => 'pilote',
    'propertyName' => 'pilote_user'
]);

$this->belongsTo('Verificateurs', [
    'className' => 'Users',
    'foreignKey' => 'no_user',
    'propertyName' => 'verificateur_user'
]);

$this->belongsTo('Users', [
    'className' => 'Users',
    'foreignKey' => 'no_user',
    'propertyName' => 'user'
]);

But when I debug my entity, the two first fields only contain the foreign key, and the last one is fine.

The query :

public function view($id = null)
{
    $demande = $this->Demandes->get($id, [
        'contain' => ['Users']
    ]);
    $this->set('demande', $demande);
    $this->set('_serialize', ['demande']);
}

Here is the output of debug() :

object(App\Model\Entity\Demande) {
'new' => false,
'accessible' => [
    'pilote' => true,
    'verificateur' => true,
    'pilote_user' => true,
    'verificateur_user' => true,
    'user' => true,
],
'properties' => [
    'no_demande' => (int) 4,
    'pilote' => (int) 3,
    'verificateur' => (int) 2,
    'no_user' => (int) 1,
    'user' => object(App\Model\Entity\User) {
        /* Details of the user */
    },
],
'dirty' => [],
'original' => [],
'virtual' => [],
'errors' => [],
'repository' => 'Demandes'
}

If I comment my last belongsTo(), the second field is fine , but not the first one.

Thanks in advance

1
What query generates this result?José Lorenzo Rodríguez
I added the query to my postJun
You need to contain the other associations 'contain' => ['Users', 'Verificateurs', 'Pilotes']José Lorenzo Rodríguez

1 Answers

4
votes

Change the name in the first argument:

$this->belongsTo('Pilotes', [
    'className' => 'Users',
    'foreignKey' => 'pilote',
    'propertyName' => 'pilote_user'
]);

$this->belongsTo('Verificateurs', [
    'className' => 'Users',
    'foreignKey' => 'verificateur',
    'propertyName' => 'verificateur_user'
]);

$this->belongsTo('Users', [
    'className' => 'Users',
    'foreignKey' => 'no_user',
    'propertyName' => 'user'
]);

Note that as you chose to use pilote and verificateur as column names in your schema, you need to change the value of propertyName. This is because Cake will create a property in your entities with that name and it will collide with the properties in your table.

That is the reason I had to choose pilote_user as a property name for your entity, for example.

When querying you data you will need to add 'contain' => ['Users', 'Verificateurs', 'Pilotes'] to the finder options