LoginSignup
2
1

More than 5 years have passed since last update.

関連テーブルを簡単保存

Last updated at Posted at 2017-09-22

少しハマってしまったので、メモ

templateファイルを少しいじると簡単にできる

Template/Articles/add.ctp
$this->Form->create($article);

// Author 入力 (belongsTo)
//下記のようにカラムの前にモデル名を記入する
echo $this->Form->control('author.first_name');
echo $this->Form->control('author.last_name');


// Tags 入力 (belongsToMany)
echo $this->Form->control('tags.0.name');
echo $this->Form->control('tags.1.name');


// belongsToMany の複数選択要素
echo $this->Form->control('tags._ids', [
    'type' => 'select',
    'multiple' => true,
    'options' => $tagList,
]);


// 結合テーブルの入力 (articles_tags)
echo $this->Form->control('tags.0._joinData.starred');
echo $this->Form->control('tags.1._joinData.starred');


// Comments 入力 (hasMany)
echo $this->Form->control('comments.0.id');
echo $this->Form->control('comments.0.comment');
echo $this->Form->control('comments.1.id');
echo $this->Form->control('comments.1.comment');

※注意※
モデル指定のとき大文字始まり複数形ではないので注意が必要

コントローラの例としては

Template/Articles/add.ctp

$article = $this->Staffs->newEntity();
if ($this->request->is('post')) {
   $article = $this->Articles->patchEntity($article, $this->request->getData());
   if ($this->Staffs->save($article)) {
        $this->Flash->success(__('登録を完了しました'));
        return $this->redirect(['action' => 'index']);
   }
     $this->Flash->error(__('登録に失敗しました'));
}

こんな感じで普通に保存すればOK
ほとんど公式のままですが、、、

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1