在将数据保存到具有多个关系的2个表中时,不保存cakephp 3.x数据
我有两个表的文章和评论,评论有字段article_id他们之间的关系我们文章hasMany评论和评论属于文章,我在我的文章/ add.ctp视图文件中有以下代码
<?php
$this->Form->create($article)
echo $this->Form->input('title');
echo $this->Form->input('status');
echo $this->Form->input('comments.0.title');
echo $this->Form->input('comments.0.description');
$this->Form->end()
?>
这是我的控制器代码
public function add() {
$article = $this->Articles->newEntity();
if ($this->request->is('post')) {
$article = $this->Articles->patchEntity($article, $this->request->data, [
'associated' => ['Commments']
]);
if ($this->Articles->save($article)) {
$this->Flash->success(__('The article has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The article could not be saved. Please, try again.'));
}
}
$this->set(compact('article'));
$this->set('_serialize', ['article']);
}
这是我的文章模型
<?php
class ArticlesTable extends Table {
public function initialize(array $config) {
parent::initialize($config);
$this->table('articles');
$this->displayField('title');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->hasMany('Comments', [
'foreignKey' => 'article_id'
]);
}
}
?>
这是我的评论模型
<?php
class CommentsTable extends Table {
public function initialize(array $config) {
parent::initialize($config);
$this->table('comments');
$this->displayField('id');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->belongsTo('Articles', [
'foreignKey' => 'article_id',
'joinType' => 'INNER'
]);
}
}
?>
当我在补丁实体之后打印$ article而不是显示下面的数组时,它没有创建注释模型对象,它在文章模型对象下创建简单数组
App\Model\Entity\Article Object
(
[title] => Article1
[status] => 1
[comments] => Array
(
[0] => Array
(
[title] => Article 1 Comment 1
[description] => mnftrduio
)
)
[[new]] => 1
[[accessible]] => Array
(
[*] => 1
)
[[dirty]] => Array
(
[title] => 1
[status] => 1
[comments] => 1
)
但是数据只保存在文章表中而不是评论表中
答案 0 :(得分:1)
您的代码没有任何问题,只是错过了一些回声,分号和错误的评论三重&#39; m&#39;
$this->Form->create($article) //missing echo and semicolon;
echo $this->Form->create($article); //the correct one
$this->Form->end() //missing submit button
echo $this->Form->button(__('Submit')); //the correct one
echo $this->Form->end(); //the correct one
$article = $this->Articles->patchEntity($article, $this->request->data, [
'associated' => ['Commments']
]); //mistype comments with triple "m"
$article = $this->Articles->patchEntity($article, $this->request->data, [
'associated' => ['Comments']
]);// the correct one
在你纠正之后,它应该工作:)