Reputation: 1312
I have two models - Cars
and CarOptions
Cars
hasOne CarOptions
If the user were to edit Cars - they can also set some CarOptions and save
Everything related to Cars
saves just fine, but CarOptions
does not save. If I were to debug the Car
object just before save - I see the following
Car: {
"id": 3,
"name": "Ford Mustang",
"description": "some description",
"city": "San Francisco",
"state": "California",
"country": "USA",
"created": "2015-08-14T12:20:14-0500",
"CarOptions": {
"manual_transmission": "N"
}
}
My code to save is as below
$car = $this->Cars->findByName('Ford Mustang')->first();
$car = $this->Cars->patchEntity($car, $this->request->data);
$carOptions = $this->Cars->CarOptions->newEntity();
$carOptions->manual_transmission = 'N';
$car->CarOptions = $carOptions;
$this->Cars->save($car);
However the CarOptions record is not created or edited. What am I missing?
Upvotes: 0
Views: 1730
Reputation: 60463
You're not following the conventions properly, see
Cookbook > Database Access & ORM > Saving Data > Saving HasOne Associations
When saving hasOne associations, the ORM expects a single nested entity at the singular, underscored version of the association name. [...]
So for an association named CarOptions
, the property to use should be car_option
.
Also note that if you want to let the user choose the option and its value, hard coding it like you're doing it isn't really the way to go, instead pass it properly in the request data, and let the marshaller do the "to entity" conversion when patching the entity.
See also
Upvotes: 6