Reputation: 4091
I have ModelA
, which "hasOne" ModelB
.
I already have a row in DB in the ModelB
table with ID 1, but modelA_id
is set to NULL
. Now I want to add a row into the ModelA
table and I want it to be associated to the row in ModelB
with ID 1.
I tried doing:
$newA = $modelATable->newEntity(["modelB_id" => 1]);
$modelATable->save($newA);
which indeed does create a new row in the ModelA
table, but the modelA_id
field in ModelB
table is not updated.
What does work is this, for example:
$newA = $modelATable->newEntity(["modelB" => ["id" => 1, "modelA_id" => $newId]]);
$modelATable->save($newA);
but this is cumbersome and not really what I want (can't know modelA_id in advance -> I would just have to update the modelA_id
field after the new row has been added)
Associations are properly set and 'modelB_id' = true
in $_accessible
in the Entity class of ModelA
.
Is this not possible or am I not understanding something right or is this just a mistake on my part somewhere? No (validation) errors are thrown when first piece of code is used, which leads me to believe that the Marshaller does not do anything with modelB_id
, it just ends up being a redundant field.
Any help is greatly appreciated!
Upvotes: 0
Views: 436
Reputation: 60503
The modelB_id
field on ModelA
doesn't make any sense in a hasOne
association, as the other table has the foreign key, which is modelA_id
, so that's why the marshaller ignores it, that is the expected behavior.
Your second variant is the correct one, however there is no need to define the foreign key, all you need to pass is the primary key, the foreign key field will be updated automatically in case the associations are set up properly, ie this is all that should be necessary for the association:
'modelB' => [
'id' => 1
]
See also
Upvotes: 1