I'm putting together a simple shopping cart system, using Laravel and Vue.js, to sell photos. Each photo comes in a range of sizes, with the price of each size being different.
I have the following tables:
Photos
- id
- title
Sizes
- id
- dimensions
Photos_Sizes
- id
- photo_id
- size_id
- price
I'm using Vue.js to make API calls to my cart controller to manipulate the cart. It passes the photo_id and size_id when the user clicks the Add to Basket button. Naturally I want to grab the price of a selected item from the database rather than client side to prevent any cheekiness, and that naturally means querying the pivot table.
My question is, using the two ids passed to the controller, how can I access the correct price value in the pivot table?
You can use Query Builder in your controller like this:
public function price(Request $request)
{
$row = DB::table('Photos_Sizes')
->where('photo_id', $request->input('photo_id'))
->where('size_id', $request->input('size_id'))
->first();
return Response::create($row->price, 200);
}
在“照片”和“尺寸”的关系上,添加->withPivot('price')
然后在设置好结果集之后,可以使用$size->pivot->price
访问该字段
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.