Struggling a bit here with converting a CakePHP2 relationship to CakePHP4.
I have a member table, and each member can have one or more “Contacts” - these are parents / guardians or “next of kin” of a member.
In CakePHP we had a member_relationships table that held the parent_id and member_id
public $belongsTo = [
'ParentMember' => [
'className' => 'Member',
'foreignKey' => 'parent_id'
],
'ChildMember' => [
'className' => 'Member',
'foreignKey' => 'member_id'
],
and in the member table
'ParentRelationship' => [
'className' => 'MemberRelationship',
'dependent' => true
],
'ChildRelationship' => [
'className' => 'MemberRelationship',
'foreignKey' => 'parent_id',
'dependent' => true
],
All works fine.
In CakePHP4 I have
$this->belongsTo('ParentMembers', [
'className' => 'Members',
'foreignKey' => 'parent_id',
]);
$this->belongsTo('ChildMembers', [
'className' => 'Members',
'foreignKey' => 'member_id',
]);
and
$this->hasMany('ParentRelationships', [
'className' => 'MemberRelationships',
'foreignKey' => 'member_id',
'dependent' => true
]);
$this->hasMany('ChildRelationships', [
'className' => 'MemberRelationships',
'foreignKey' => 'parent_id',
'dependent' => true
]);
All is going fine except where I am trying to add a new relationship where a “Contact” (eg a parent) doesn’t exit- what I’m find is the id of the new Parent isn’t being saved in the parent_id field
$memberRelationship = $this->MemberRelationships->newEmptyEntity();
if ($this->request->is('post')) {
$memberRelationship = $this->MemberRelationships->patchEntity($memberRelationship, $this->request->getData(), [
'associated' => [
'ParentMembers'
]]);
I’m thinking the MemberRelationship record is being saved before the new “ParentMember” and so the parent_id is empty. Use to use “SaveAssociated” in CakePHP2