【发布时间】:2017-05-22 20:45:29
【问题描述】:
我有一个关于使用 CakePhp 3 保存关联数据的问题。不幸的是,我无法弄清楚问题出在哪里。我的场景很简单。我想保存以下请求数据:
$data = [
'name' => 'article 1',
'comments' => [
(int) 0 => [
'description' => 'comment 1'
]
]
]
在这种情况下。我想用一个新的评论实体保存一个新的文章实体。因此,对于这两个实体来说,它都是表中的新记录。所以有文章表和 cmets 表,其中每条评论都与文章表有关联。
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 错误:
错误:SQLSTATE[42000]:语法错误或访问冲突:1064 你 您的 SQL 语法有错误;检查对应的手册 您的 MySQL 服务器版本,以便在“描述”附近使用正确的语法, 创建,修改)值(3,'comment 1','2017-05-22 20:36:59','2017-05-22 20:3' 在第 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 中通常一直这样做的方式。很抱歉问了这么简单的问题。我就是想不通。那么我在这里想念什么吗?有人能看出我的错吗?
【问题讨论】:
-
描述栏的类型是什么?
-
简单的 VARCHAR 255 允许 NULL
-
这是正确的做法。您的字段类型是否正确?
-
是的,一切都是正确的。我的代码也已烘焙,所以该部分应该没有错误吧?
-
您发布的代码没有错误。如果您将
$article传递给 ArticlesTable 的save(),它应该会保存它。
标签: php mysql cakephp cakephp-3.0