getting the value of an extra pivot table column laravel

旧街凉风 提交于 2019-11-27 11:26:06

When using Many to Many relationships with Eloquent, the resulting model automatically gets a pivot attribute assigned. Through that attribute you're able to access pivot table columns. Although by default there are only the keys in the pivot object. To get your columns in there too, you need to specify them when defining the relationship:

return $this->belongsToMany('Role')->withPivot('foo', 'bar');

Official Docs

If you need more help the task of configuring the relationships with Eloquent, let me know.

Edit

To query the price do this

$model->problems()->where('phone_problem', $problem->id)->first()->pivot->price

To get data from pivot table:

$price = $model->problems()->findOrFail($problem->id, ['phone_problem'])->pivot->price;

Or if you have many records with different price:

$price = $model->problems()->where('phone_problem', $problem->id)->firstOrFail()->pivot->price;

In addition.

To update data in the pivot you can go NEW WAY:

$model->problems()->sync([$problemId => [ 'price' => $newPrice] ], false); 

Where the 2nd param is set to false meaning that you don't detach all the other related models.

Or, go old way

$model->problems()->updateExistingPivot($problemId, ['price' => $newPrice]);

And remind you:

To delete:

$model->problems()->detach($problemId);

To create new:

$model->problems()->attach($problemId, ['price' => 22]);

It has been tested and proved working in Laravel 5.1 Read more.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!