CakePHP 3 不保存 hasOne 关联

CakePHP 3 not saving hasOne associations

我有两个模型 - CarsCarOptions

Cars 有一个 CarOptions

如果用户要编辑汽车 - 他们还可以设置一些汽车选项并保存

所有与Cars相关的都保存好了,但是CarOptions不保存。如果我要在保存之前调试 Car 对象 - 我会看到以下内容

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"
    }
}

我要保存的代码如下

$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);

但是,没有创建或编辑 CarOptions 记录。我错过了什么?

您没有正确遵守约定,请参阅

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. [...]

因此对于名为 CarOptions 的关联,要使用的 属性 应该是 car_option

另请注意,如果您想让用户选择选项及其值,像您正在做的那样对其进行硬编码并不是真正可行的方法,而是在请求数据中正确传递它,并且让编组器在修补实体时进行 "to entity" 转换。

另见