Save data associated with CakePHP 3

1

Good afternoon. I am trying to save associated data in CakePHP 3. For this, I created three tables: sales (id, customer_name), products (id, product) and sales_products (id, id_products, sales_id).

On sale table I realized the association:

$this->belongsToMany('Produtos', [
 'foreignKey' => 'vendas_id',
 'targetForeignKey' => 'produtos_id',
 'joinTable' => 'produtos_vendas'
]);

On products table I have realized the association:

$this->belongsToMany('Vendas', [
 'foreignKey' => 'produtos_id',
 'targetForeignKey' => 'vendas_id',
 'joinTable' => 'produtos_vendas'
]);

In the sales controller I saved with the following data:

{ 
  "nome_cliente": "João",
  "produto": "maça"
}

Using the code:

$venda = $this->Vendas->newEntity();

$venda = $this->Vendas->patchEntity($venda, $this->request->data);

if ($this->Vendas->save($venda)) {
    $this->Flash->success(__('The venda has been saved.'));
} else {
    $this->Flash->error(__('The venda could not be saved. Please, try again.'));
}

The data is saved in the sales table, but it is not saved in the associative table. Can someone help me please?

    
asked by anonymous 08.11.2016 / 18:19

1 answer

0

The error was in the "date". I was missing the id (s) of the "products" table. Instead of passing:

{ 
  "nome_cliente": "João",
  "produto": "maça"
}

I should pass:

{ 
  "nome_cliente": "João",
  "produtos": [{"id": 12}, {"id": 26}, {"id": 50}]
}

So I refer to which products (from your id) I want to relate to an entity from the sales table.

    
09.11.2016 / 23:48