Does patchEntity support multiple _joinData for same associations?

POSTing data as per example in the book works fine for a single association to the same record, but not multiple.

Let’s say, that you want to save multiple records for same student and course

$data = [
    'first_name' => 'Sally',
    'last_name' => 'Parker',
    'courses' => [
        [
            'id' => 10,
            '_joinData' => [
                'grade' => 80.12,
                'days_attended' => 30
            ]
        ],
        [
            'id' => 10,
            '_joinData' => [
                'grade' => 11.11,
                'days_attended' => 1111
            ]
        ]
        // Other courses.
    ]
];

But if I try to patchEntity with the following example, only 1 association is created

{
    "first_name": "First name",
    "last_name": "Last name",
    "egroups": [
        {"id": 4, "_joinData": {"role": "user"}},
        {"id": 4, "_joinData": {"role": "contact"}}
    ]
}

Doing the same thing from code works without issues

$cet = $this->getTableLocator()->get('ContactsEgroups');
$contact = $this->Contacts->get(1480);

$egroups_table = $this->getTableLocator()->get('Egroups');
$group1 = $egroups_table->get(4);
$group1->_joinData = new Entity(['role' => 'user']);

$group2 = $egroups_table->get(4);
$group2->_joinData = new Entity(['role' => 'contact']);

$this->Contacts->Egroups->replaceLinks($contact, [$group1, $group2]);

The marshaller only supports unique foreign key pairs for the join table. You need to use hasMany association for your use case.

1 Like

Thx for your answer. Could you please elaborate further?

As per book many to many associations are done using belongsToMany where as one to many are done using hasMany. Cake bake has generated the relation with belongsToMany
$this->belongsToMany('Egroups', [
'foreignKey' => 'contact_id',
'targetForeignKey' => 'egroup_id',
'joinTable' => 'contacts_egroups',
]);

If I switch it to hasMany, patchEntity tries to generate new group entities.

I intentionally used the book example students - courses for clarity. Only difference is that in my case I need to link same entities multiple times with different data in join table.