I have models Transaction
and Option
, that have many to many relationship. The pivot table transaction_options
has columns transaction_id
, option_id
and price
.
I have defined the relationships in the models like this:
Transaction model:
public function options()
{
return $this->belongsToMany('App\Option', 'transaction_options')->withPivot('price');
}
Option model:
public function transactions()
{
return $this->belongsToMany('App\Transaction', 'transaction_options')->withPivot('price');
}
I am wondering how can I save something in the pivot table, I have tried something like this, but it is not working:
foreach($data->options as $option) {
$transaction->options()->create([
'transaction_id' => $transaction->id,
'extras_id' => $option->extraId,
'option_id' => $option->id,
'price' => $option->price
]);
}
How can I do this?
Route::get('/', function () { $user = \App\User::find(2); $job = \App\Job::with('notifications')->find(3); $job->notifications->is_accepted = 'Y'; // is_accepted is pivot table's column $notification = $user->notifications()->save($job); });
Many to Many relations is one of the eloquent relationships in Laravel. The main factor in many many relations is the to join table that is called the pivot table. The pivot table has the ability to perform relations from one model to many models.
In laravel, When working in a many-many relationship, the user has to choose the intermediate table and it is called a pivot table in terms of Laravel. The pivot attribute communicates with this intermediate table in controllers or models in Laravel. The admin in laravel has to define the role of every other user.
Pass the extra field as a value to attach function
$transaction->options()->attach([$request['id'] => ['price' => $request['price']]]);
https://laravel.com/docs/master/eloquent-relationships#updating-many-to-many-relationships
From what I can see, you should use your code like this:
foreach ($data->options as $option) {
$transaction->options()->attach($option->id, ['price' => $option->price])
}
You can pass pivot data as the second parameter:
foreach($data->options as $option) {
$transaction->options()->create(
['extras_id' => $option->extraId],
['price' => $option->price]
);
}
You also don't need to pass both transaction_id
and option_id
, they will be inserted automatically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With