Insert Many to Many Laravel 5.5

Asked

Viewed 531 times

1

I’m doing a data insertion on a form where it contains data of a relation many for many (Many to Many), my difficulty is in inserting in the pivot table more than one reference data, follow post below:

inserir a descrição da imagem aqui

As we can see, I have the following array:

  • selected source list
  • address_value

They have the id of fornecedor relating to the produto and a value for each fornecedor, if only to insert the id of referencia, I saw that it is done this way, example:

$insert = Product::create($data_form);
$providers = $insert->providers()->attach(1);

I would like to know how to send besides the id, the value for that fornecedor, follows below as this my model and as an example the data already in the database:

Model:

public function providers()
{
    return $this->belongsToMany(Provider::class)
                ->withPivot(['value', 'created_at', 'updated_at']);
}

Bench:

inserir a descrição da imagem aqui

According to the guidelines, I mentioned and encountered the following problem:

My new code tree:

$value_providers = array();
foreach ($data_form['lista_fornecedor_valor'] as $key => $value) {
    $value_providers[] = number_format((float)$value, 2, '.', ',');
}

$providers = $insert->providers()->attach($data_form['lista_fornecedor_selecionado'], ['value' => $value_providers]);

returns me this error:

Array to string conversion (SQL: insert into `product_provider` (`created_at`, `product_id`, `provider_id`, `updated_at`, `value`) values (2017-10-14 20:50:19, 5782, 1, 2017-10-14 20:50:19, 20.00), (2017-10-14 20:50:19, 5782, 6, 2017-10-14 20:50:19, 20.00))

Another point is that in sql the 2 values are with the value of the 1 array, not sequential:

example:

$value_providers = ['20.00', '15.00']
  • Renan has to record item by item, so do a go and pass one by one

  • understood, codei this way and it worked, thanks for the help.

  • Do not fail to accept as an answer

1 answer

1


If your doubt is insert into the Many to Many Laravel following the documentation stays:

$insert = Product::create($data_form);
if ($insert) // foi inserido.
{
    $providers = $insert->providers()->attach(1, ['value' => 9.75]);
}

that is, after informing the id, pass an array of additional information to record in this many table for many that has additional fields.

Observing: the values in the minimum form example set can use the variables.

Reference: Many To Many Relationships

  • put more data in the question!!!

Browser other questions tagged

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