cakephp3 アソシエーション
投稿:Postsに複数のコメント:Comments まとめて保存
PostsTable.php
public function initialize(array $config)
{
$this->hasMany('comments', [
'foreignKey' => 'post_id'
]);
}
add.ctp
<?php
echo $this->Form->input('title');
echo $this->Form->input('comments.0.item_name');
echo $this->Form->input('comments.0.item_price');
echo $this->Form->input('comments.0.qty');
PostsController.php
, [‘associated’ => [‘comments’]] 追加
if ($this->request->is('post')) {
$post = $this->Posts->patchEntity($post, $this->request->data, ['associated' => ['comments']]);
if ($this->Posts->save($post)) {
$this->Flash->success(__('The post has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The post could not be saved. Please, try again.'));
}
}