[英]CakePhp 3 - save associated model failed and ended in mysql error
我有一個關於使用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錯誤:
錯誤:SQLSTATE [42000]:語法錯誤或訪問沖突:1064您的SQL語法有錯誤。 檢查與您的MySQL服務器版本相對應的手冊,以在'描述,創建,修改的''附近使用正確的語法VALUES(3,'注釋1','2017-05-22 20:36:59','2017-05 -22 1行的-22 20:3'
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.