Save Data Associated with Cakephp 3

Asked

Viewed 141 times

1

Good afternoon. I am trying to save associated data in Cakephp 3. For this I have created three tables: sales(id, customer name), products(id, product) and sales(id, products_id, sales_id).

On sale table I held association:

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

In table products I performed 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.'));
}

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

1 answer

0


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

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

I should pass:

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.