07S*_*ect 6 cakephp save model-associations associated-object cakephp-3.0
我正在学习 cakePHP 3.0 并且在我的模型上保存相关数据时遇到了一些问题。
我尝试使用 ClientPreferences 的关联数据保存客户端
客户表
class ClientsTable extends Table
{
public function initialize(array $config)
{
(...)
$this->belongsTo('ClientPreferences', [
'foreignKey' => 'client_preferences_id'
]);
}
}
Run Code Online (Sandbox Code Playgroud)
客户端控制器
$aClient = $this->Clients->newEntity();
$aClient = $this->Clients->patchEntity($aClient, $this->request->data);
$aClientPreference = $this->Clients->ClientPreferences->newEntity();
$aClientPreference->my_field = 'my value';
$aClient->ClientPreferences = $aClientPreference;
$this->Clients->save($aClient, ['associated' => ['ClientPreferences']];
Run Code Online (Sandbox Code Playgroud)
Client 实体已正确保存,但关联的 ClientPreferences 实体未正确保存,并且 Cake 没有抛出错误。
我试图遵循这个:http : //book.cakephp.org/3.0/en/orm/saving-data.html# Saving-with-associations
但还没有发现任何问题来正确地做。有人有什么建议吗?
先感谢您。
您链接的示例显然存在差异,仔细查看属性名称,如果再向下滚动一点,您会找到专门针对belogsTo关联的解释。
保存belongsTo 关联时,ORM 期望在关联名称的单数、下划线版本处有一个嵌套实体。例如: [...]
Cookbook > 保存数据 > 保存 BelongsTo 关联
因此,对于belongsTo关联,属性名称默认为小写和下划线,即$aClient->client_preference.
你的外键应该顺便说一句。也是单数以匹配约定,即client_preference_id,即使它只是导致问题的属性名称。
另请参阅Cookbook > Associations > BelongsTo Associations(尤其是foreignKey和propertyName选项)