Products
belongsToMany ProductCircles
through ProductsInCircles
.
ProductsInCirclesTable.php
public function initialize(array $config)
{
$this->table('products_in_circles');
$this->displayField('id');
$this->primaryKey('id');
$this->belongsTo('Products', [
'foreignKey' => 'product_id'
]);
$this->belongsTo('ProductCircles', [
'foreignKey' => 'product_circle_id'
]);
}
ProductsTable.php
public function initialize(array $config)
{
$this->table('products');
$this->displayField('name');
$this->primaryKey('id');
$this->belongsToMany('ProductCircles', [
'through' => 'ProductsInCircles',
]);
}
When I edit a Product
via products/edit/{id}
, I will provide the following data from $this->request->data
Array
(
[name] => Piuma
[attributes_in_json] => {"size":"large"}
[rooms] => Array
(
[0] => 2
)
[styles] => Array
(
[0] => 15
[1] => 16
)
[materials] => Array
(
[0] => 27
)
[product_circles] => Array
(
[_ids] => Array
(
[0] => 2
[1] => 15
[2] => 16
[3] => 27
)
)
[associated] => Array
(
[0] => ProductCircles
)
)
The following code did not save the associated data into products_in_circles
table
$product = $this->Products->patchEntity($product, $this->request->data);
$product->dirty('product_circles', true);
if ($this->Products->save($product)) {
I have also tried
$product = $this->Products->patchEntity($product, $this->request->data, ['associated' => ['ProductCircles']]);
if ($this->Products->save($product)) {
AND
$product = $this->Products->patchEntity($product, $this->request->data);
if ($this->Products->save($product, ['associated' => ['ProductCircles']])) {
AND
$product = $this->Products->patchEntity($product, $this->request->data, ['ProductCircles']);
if ($this->Products->save($product)) {
How do I save and persist these into the products_in_circles
table properly?
I definitely want to use the append
option as well instead of replace
.
I have looked at the docs and the example is clearer for creating new entity. Mine is for editing an existing entity.
Also, I cannot find out where I turn on the append
option. See http://book.cakephp.org/3.0/en/orm/saving-data.html#saving-belongstomany-associations
I suspect I made a mistake in the way the data is structured.
Please advise.
EDIT
Product Entity
class Product extends Entity
{
/**
* Fields that can be mass assigned using newEntity() or patchEntity().
*
* @var array
*/
protected $_accessible = [
'name' => true,
'attributes_in_json' => true,
'created_by' => true,
'modified_by' => true,
'prices' => true,
];
}
product_circles
property accessible in your Product entity class? – José Lorenzo Rodríguez