gpt4 book ai didi

php - CakePhp 3 - 保存关联模型失败并以 mysql 错误结束

转载 作者:行者123 更新时间:2023-11-29 10:48:45 24 4
gpt4 key购买 nike

我有一个关于使用 CakePhp 3 保存关联数据的问题。不幸的是,我不知道问题出在哪里。我的场景很简单。我想保存以下请求数据:

$data = [
'name' => 'article 1',
'comments' => [
(int) 0 => [
'description' => 'comment 1'
]
]
]

在这种情况下。我想用新的评论实体保存一个新的文章实体。因此对于这两个实体来说,它都是表中的新记录。因此,有文章表和评论表,其中每个评论都与文章表有连接。

ArticlesTable.php

    $this->hasMany('Comments', [
'foreignKey' => 'article_id'
]);

CommentsTable.php

$this->belongsTo('Articles', [
'foreignKey' => 'article_id',
'joinType' => 'INNER'
]);

修补文章

$article = $this->Articles->patchEntity($article, $data, [
'associated' => [
'Comments'
]
]);

调试打印 - 修补文章

object(App\Model\Entity\Article) {

'name' => 'article 1',
'comments' => [
(int) 0 => object(App\Model\Entity\Comment) {

'description' => 'comment 1',
'[new]' => true,
'[accessible]' => [
'*' => true
],
'[dirty]' => [
'description' => true
],
'[original]' => [],
'[virtual]' => [],
'[errors]' => [],
'[invalid]' => [],
'[repository]' => 'Comments'

}
],
'[new]' => true,
'[accessible]' => [
'*' => true
],
'[dirty]' => [
'name' => true,
'duration' => true,
'comments' => true
],
'[original]' => [],
'[virtual]' => [],
'[errors]' => [],
'[invalid]' => [],
'[repository]' => 'Articles'

}

SQL 错误:

Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'description, created, modified) VALUES (3, 'comment 1', '2017-05-22 20:36:59', '2017-05-22 20:3' at line 1

SQL 查询:

BEGIN
INSERT INTO articles (name, created, modified)
VALUES
(
'article 1', '2017-05-22 20:36:59',
'2017-05-22 20:36:59'
)
INSERT INTO comments (
article_id, description, created, modified
)
VALUES
(
3, 'comment 1', '2017-05-22 20:36:59', '2017-05-22 20:36:59'
)
ROLLBACK

这里非常详细地介绍了我正在做的所有事情。我只是很困惑,因为据我记得这是我在 Cakephp 3 中通常这样做的方式。很抱歉问这么简单的问题。我就是想不通。那么我在这里错过了什么吗?有人能看出我的错吗?

最佳答案

您不需要在cakephp3中编写简单实体插入的SQL查询,请查看https://book.cakephp.org/3.0/en/orm/saving-data.html

在您的文章中添加操作,您应该使用 $this->Articles->save();

if $this->request->is('post') {

$article = $this->Articles->newEntity($this->request->data());

$this->Articles->save($article);

}

关于php - CakePhp 3 - 保存关联模型失败并以 mysql 错误结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44121871/

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