Reputation: 2306
i have a question about saving associated data with CakePhp 3. Unfortunately I can't figure out what's the problem is. My scenario is very easy. I want to save the following request-data:
$data = [
'name' => 'article 1',
'comments' => [
(int) 0 => [
'description' => 'comment 1'
]
]
]
In this case. I want to save a new article-entity with a new comment-entity. So for both entities it's a new record in the table. So there's is the articles-table and a comments-table where each comment has a connection to the article-table.
ArticlesTable.php
$this->hasMany('Comments', [
'foreignKey' => 'article_id'
]);
CommentsTable.php
$this->belongsTo('Articles', [
'foreignKey' => 'article_id',
'joinType' => 'INNER'
]);
Patched Article
$article = $this->Articles->patchEntity($article, $data, [
'associated' => [
'Comments'
]
]);
Debug Print - Patched Article
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:
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 Query:
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
Here's super detailed all the stuff what I'm doing. I am just confused cause as far as I remember this is the way how I normally do it all the time in Cakephp 3. Sorry to ask such a simple question. I just can't figure it out. So do I miss something here? Can someone see my fault?
Upvotes: 0
Views: 323
Reputation: 261
You shouldn't need to write SQL queries for simple entity insertion in cakephp3, please have a look at https://book.cakephp.org/3.0/en/orm/saving-data.html
In your articles add action you should use $this->Articles->save();
if $this->request->is('post') {
$article = $this->Articles->newEntity($this->request->data());
$this->Articles->save($article);
}
Upvotes: 1