I have 4 tables: products
, tags
, categories
and taxonomy_to_products
. The table contains data that links tags
and products
together, same with category
and products
.
When I am trying to link existing category to products it’s not updating on the taxonomy_to_products
table.
Here is my taxonomy_to_products
table screenshot
Model\Table\CategoriesTable:-
$this->belongsToMany('Products', [
'targetForeignKey' => 'product_id',
'foreignKey' => 'category_id',
'joinTable' => 'taxonomy_to_products',
'saveStrategy' => 'replace'
]);
Model\Table\TagsTable:-
$this->belongsToMany('Products', [
'targetForeignKey' => 'product_id',
'foreignKey' => 'tag_id',
'joinTable' => 'taxonomy_to_products',
'saveStrategy' => 'replace'
]);
Model\Table\ProductsTable:-
$this->belongsToMany('Tags', [
'foreignKey' => 'product_id',
'targetForeignKey' => 'tag_id',
'joinTable' => 'taxonomy_to_products',
'saveStrategy' => 'replace'
]);
$this->belongsToMany('Categories', [
'foreignKey' => 'product_id',
'targetForeignKey' => 'category_id',
'joinTable' => 'taxonomy_to_products',
'saveStrategy' => 'replace'
]);
Model\Table\TaxonomyToProducts:-
$this->belongsTo('Categories', [
'foreignKey' => 'category_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Tags', [
'foreignKey' => 'tag_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Products', [
'foreignKey' => 'product_id',
'joinType' => 'INNER'
]);
This is my action
public function edit($id = null) {
$product = $this->Products->get($id, [
'contain' => [
'Media' => ['fields' => ['id', 'url']],
'Categories',
'Tags',
]
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$product = $this->Products->patchEntity($product, $this->request->getData(), ['associate' => ['Categories']]);
//print_r($$product);exit();
if ($this->Products->save($product)) {
$this->Flash->success(__('The product has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The product could not be saved. Please, try again.'));
}
$allCategories = $this->Products->Categories->find('treeList', [
'keyPath' => 'id',
'valuePath' => 'name',
'spacer' => '⚊',
])->toArray();
$this->set(compact('product', 'allCategories'));
}
This is my Form:-
<?= $this->Form->select('categories._ids', $allCategories, ['hiddenField' => false, 'multiple' => 'checkbox', 'escape' => false])?>