I am new to Laravel framework. To be exact, I'm using Laravel 5.6 now. Recently I have some problem with insertion of many-to-many relation with an array of extra attributes.
Here is my script:
$data = [
"produk_id" => [
0 => 17,
1 => 7,
2 => 2,
],
"tarif" => [
29290,
119395,
89873,
],
"qty" => [
0 => 4,
1 => 6,
2 => 13,
],
];
Transaksi::find(1)->produk()->attach($data['produk_id'], ['tarif'=>$data['tarif']]);
It gives me this error:
It is strange that the query produced seems to be true. But warn by some exception.
So, i then change the strategy to map the tarif array that suit to the Eloquent documentation like this:
$data_tarif = array_map(function ($item) {
return ['tarif' => $item];
}, $data['tarif']);
And then pass it to second parameter of attach as extra attributes:
Transaksi::find(1)->produk()->attach($data['produk_id'], $data_tarif);
But it still gives me an exception, even so far from my expectation:
Am I wrong to use that attach method with multiple arrays of an extra attribute? Since I've tried with a simple array or Laravel documentation, but they seem not work well. what should I do to fix them?
Some attachment to help:
This is my Transaksi model and Produk model
class Transaksi extends Model
{
protected $table = 'transaksi';
public function user()
{
return $this->belongsTo(User::class, 'user_id');
public function customer()
{
return $this->belongsTo(Customer::class, 'customer_id');
}
public function produk()
{
return $this->belongsToMany(Produk::class, 'detail_transaksi');
}
}
class Produk extends Model
{
protected $table = 'produk';
public function transaksi()
{
return $this->belongsToMany(Transaksi::class, 'detail_transaksi');
}
}
try this:
$attachArray = array();
foreach ($data['produk_id'] as $index => $id) {
$attachArray[$id] = ['tarif' => $data['tarif'][$index]];
}
Transaksi::find(1)->produk()->attach($attachArray);