как сохранить ownToMany для редактирования в CakePHP 3.x?

Products принадлежитToMany с ProductCircles по 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',
    ]);
}

Когда я редактирую Product через products/edit/{id}, я предоставлю следующие данные из $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
        )

)

Следующий код не сохранил связанные данные в таблицу products_in_circles

$product = $this->Products->patchEntity($product, $this->request->data);
$product->dirty('product_circles', true);
if ($this->Products->save($product)) {

я тоже пробовал

$product = $this->Products->patchEntity($product, $this->request->data, ['associated' => ['ProductCircles']]);
if ($this->Products->save($product)) {

И

$product = $this->Products->patchEntity($product, $this->request->data);
if ($this->Products->save($product, ['associated' => ['ProductCircles']])) {

И

$product = $this->Products->patchEntity($product, $this->request->data, ['ProductCircles']);
if ($this->Products->save($product)) {

Как правильно сохранить и сохранить их в таблице products_in_circles?

Я определенно хочу использовать опцию append вместо replace.

Я просмотрел документы, и пример стал более понятным для создания нового объекта. Мой предназначен для редактирования существующего объекта.

Также не могу найти где включить опцию append. См. http://book.cakephp.org/3.0/en/orm/saving-data.html#saving-belongstomany-associations

Я подозреваю, что ошибся в том, как структурированы данные.

Пожалуйста, порекомендуйте.

ИЗМЕНИТЬ

Продукт

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,
    ];
}

person Kim Stacks    schedule 22.03.2015    source источник
comment
доступно ли свойство product_circles в вашем классе объектов Product?   -  person José Lorenzo Rodríguez    schedule 22.03.2015
comment
добавлен код сущности продукта. Нет, у меня нет product_circles в качестве доступного свойства. Это важно?   -  person Kim Stacks    schedule 06.04.2015
comment
Ладно, похоже, это было необходимо. Спасибо, Лоренцо.   -  person Kim Stacks    schedule 06.04.2015
comment
Вы выяснили, где использовать опцию добавления?   -  person Karl Campbell    schedule 17.06.2016


Ответы (1)


Необходимо добавить product_circles в качестве доступного свойства в классе сущностей Product.

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' => true,
    ];
}

Кредит принадлежит Хосе Лоренцо в разделе комментариев.

person Kim Stacks    schedule 06.04.2015