CakePHP3.6でbelongsToManyの実装を行っています。
端的にいうと更新(insert, update)されなくて困っております。
またこれに関しては下記のチュートリアルを元に行っております。
https://book.cakephp.org/3.0/ja/tutorials-and-examples/cms/tags-and-users.html
以下の設定などに抜けなどがあれば教えてくださいませ
DBの構造
sql
1## 製品テーブル 2CREATE TABLE `products` ( 3 `id` int(11) NOT NULL AUTO_INCREMENT, 4 `name` varchar(255) NOT NULL, 5 PRIMARY KEY (`id`) 6) 7## 情報タグテーブル 8CREATE TABLE `tags` ( 9 `id` int(11) NOT NULL AUTO_INCREMENT, 10 `name` varchar(255) NOT NULL, 11 PRIMARY KEY (`id`) 12) 13## joinテーブル 14CREATE TABLE `products_tags` ( 15 `id` int(11) NOT NULL AUTO_INCREMENT, 16 `product_id` int(11) NOT NULL, 17 `tag_id` int(11) NOT NULL, 18 PRIMARY KEY (`id`) 19)
modelの設定
ProductsTable.php(Table)
php
1 $this->belongsToMany('Tags', [ 2 'foreignKey' => 'product_id', 3 'targetForeignKey' => 'tag_id', 4 'joinTable' => 'products_tags' 5 ]);
TagsTable.php(Table)
php
1 $this->belongsToMany('Products', [ 2 'foreignKey' => 'tag_id', 3 'targetForeignKey' => 'product_id', 4 'joinTable' => 'products_tags' 5 ]);
Product.php(Entity)
php
1 protected $_accessible = [ 2 'name' => true, 3 'tags' => true 4 ];
Tag.php(Entity)
php
1 protected $_accessible = [ 2 'name' => true, 3 'products' => true 4 ];
該当部分の更新部分のソースコード
ProductsController.php
php
1 public function edit($id = null) 2 { 3 4 $product = $this->Products->get($id, ['contain' => ['Tags']]); 5 if ($this->request->is(['patch', 'post', 'put'])) { 6 $product = $this->Products->patchEntity($product, $this->request->getData()); 7 if ($this->Products->save($product)) { 8 $this->Flash->success(__('更新しました')); 9 return $this->redirect(['action' => 'view', $product->id]); 10 } 11 $this->Flash->error(__('更新失敗')); 12 } 13 $tags = $this->Products->Tags->find('list'); 14 $this->set(compact('product', 'tags')); 15 }
edit.ctp
php
1 2<?= $this->Form->control('tag._ids', ['options'=>$tags, 'multiple' => true]); ?> 3
試したこと
save時、patchEntity時に下記の項目の追加をしてみましたが
php
1$this->Products->patchEntity($product, $this->request->getData(), ['associated'=>['Tags']])
php
1$this->Products->save($product, ['associated'=>['Tags']])