gpt4 book ai didi

Cakephp 3.0 保存关联模型

转载 作者:行者123 更新时间:2023-12-02 11:08:12 25 4
gpt4 key购买 nike

我正在学习 cakePHP 3.0,并且在我的模型上保存关联数据时遇到一些问题。

我尝试保存具有 ClientPreferences 关联数据的客户端

客户表

class ClientsTable extends Table
{
public function initialize(array $config)
{
(...)
$this->belongsTo('ClientPreferences', [
'foreignKey' => 'client_preferences_id'
]);
}
}

客户端 Controller

$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']];

Client 实体已正确保存,但关联的 ClientPreferences 实体未正确保存,并且 Cake 没有抛出错误。

我试图遵循这一点: http://book.cakephp.org/3.0/en/orm/saving-data.html#saving-with-associations

但尚未发现任何正确执行此操作的问题。有人有建议吗?

提前谢谢您。

最佳答案

惯例,惯例,惯例

您链接的示例显然存在差异,请仔细查看属性名称,如果您进一步向下滚动,您会找到专门针对 belogsTo 的解释协会。

When saving belongsTo associations, the ORM expects a single nested entity at the singular, underscored version of the association name. For example: [...]

<强> Cookbook > Saving Data > Saving BelongsTo Associations

因此,对于 belongsTo 关联,默认情况下属性名称应为小写并带下划线,即 $aClient->client_preference

顺便说一句,你的外键应该。为了匹配约定,也必须是单数,即 client_preference_id,即使它只是导致问题的属性名称。

另请参阅 Cookbook > Associations > BelongsTo Associations (尤其是 foreignKeypropertyName 选项)

关于Cakephp 3.0 保存关联模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29655267/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com