【发布时间】:2026-02-04 18:15:02
【问题描述】:
请问如何在CakePHP3中使用REST保存相关数据?
以免假设我有以下关联命令可以有许多相关标签(请参见下面的 EER 图)。
JSON 请求结构如下:
{
"command": "whoami",
"description": "SOMETHING",
"public": false,
"tags": [
{"name":"TEST1"},
{"name":"TEST2"}
]
}
我尝试使用
实现关联保存https://book.cakephp.org/3.0/en/orm/saving-data.html#saving-with-associations
但没有运气。
所以我是按照以下方式进行的:
public function add()
{
$this->request->allowMethod(['post']);
$data = $this->request->getData();
$user = $this->CommonHelper->getUserByToken($this->token);
$command = $this->Commands->newEntity($data);
$tags = $data['tags'];
$command->user = $user;
$command = $this->Commands->patchEntity($command, $data);
if ($this->Commands->save($command)) {
if($tags != null)
$this->addTags($tags, $command);//TODO: DO IT IN THE RIGHT WAY WITH MARSHALLING
$this->apiResponse['data'] = $command;
$this->httpStatusCode = 200;
} else {
$this->httpStatusCode = 400;
}
}
private function addTags($tags, $command)
{
foreach ($tags as $value) {
$tag = $this->Tags->newEntity($value);
$tag->commands_id = $command->id;
$this->Tags->save($tag);
}
}
但这是唯一的临时解决方案,我想以正确的方式使用 CakePHP ORM 架构的可能性。
标签表定义如下:
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('tags');
$this->setDisplayField('name');
$this->setPrimaryKey('id');
$this->belongsTo('Commands', [
'foreignKey' => 'commands_id',
'joinType' => 'INNER'
]);
}
感谢您的建议。
【问题讨论】:
-
您表明您的
Tags表与Commands具有belongsTo关联。但是Commands是否与Tags有对应的hasMany关联? -
不,它没有hasMany assoc。我认为在控制台中烘焙模型期间,应该根据 EER 方案(SQL 结构)自动添加这个 assoc。这意味着使用 $this->hasMany('Tags');我可以根据提供的 JSON 数据自动插入相关表吗?
-
您的架构不遵循CakePHP's naming conventions,外键应该是单数,因此烘焙无法正常工作。除非您明确指定不规则外键,否则手动添加的关联也不起作用。
-
谢谢,现在它可以开箱即用了。
标签: cakephp orm marshalling