Cannot change field (id) related to another table

Hey there

I have a simple relation issue. Using a contacts table and users table.
Now on the contacts table (beside a ton of fields), I have two fields, that should be related to the users table:

partner (integer)
owner (integer)

As usual I created the relations in the table (on both sides ofc):

// src/Model/Table/ContactsTable.php
$this->belongsTo('Partner', [
    'className' => 'Users',
    'foreignKey' => 'partner',
    'propertyName' => 'partner'
]);
$this->belongsTo('Owner', [
    'className' => 'Users',
    'foreignKey' => 'owner',
    'propertyName' => 'owner'
]);

and the Users table:

// src/Model/Table/UsersTable.php
$this->hasMany('Partner', [
    'className' => 'Contacts',
    'foreignKey' => 'partner',
    'propertyName' => 'partner'
]);
$this->hasMany('Owner', [
    'className' => 'Contacts',
    'foreignKey' => 'owner',
    'propertyName' => 'owner'
]);

Already existing entries do output the related fields (of course, if added contain in the controller). But I have an issue with patching (or say updating) or creating a new entity.

Before update:

'contact_partner' => (int) 2
'owner' => (int) 1

After $contact = $this->Contacts->patchEntity($contact, $this->request->getData());

// debug($this->request->getData())
'contact_partner' => '2',
'owner' => '1',

// debug($contact) -- after 'patchEntity()'
'contact_partner' => null
'owner' => null

What am I missing here? The relations work (on both sides, tested in UsersController with contain, and working on the Contacts side. But updating/creating results in null.

Thanks in advance.

Oh. PS: I am using Cake 4.0.4

Okay, somehow i fixed it.
Didn’t know what to do, so I updated the table’s row’s to:

 - owner_id		int(11)
 - partner_id	int(11)

Then I rebaked the model and added the className to the relations:

$this->belongsTo('Owners', [
    'foreignKey' => 'owner_id',
    'joinType' => 'INNER',
    'className' => 'Users'
]);
$this->belongsTo('Partners', [
    'foreignKey' => 'partner_id',
    'joinType' => 'INNER',
    'className' => 'Users'
]);

And suddenly it works. Maybe it is related to the naming convention in cake and we have to use _id to related fields (sadly somehow, if it’s true).

Whatever. It works now :slight_smile:

You don’t have to use _id, but your original configuration was telling it that owner should be used for both the integer id and the entity that it references, and likewise for partner. You could change that, but following the convention of including _id will make a lot of things easier for you.

1 Like