简体   繁体   English

如何在数据透视表(Laravel)中访问此值?

[英]How can I access this value in a pivot table (Laravel)?

I'm putting together a simple shopping cart system, using Laravel and Vue.js, to sell photos. 我正在使用Laravel和Vue.js组合一个简单的购物车系统来出售照片。 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. 我正在使用Vue.js对购物车控制器进行API调用以操纵购物车。 It passes the photo_id and size_id when the user clicks the Add to Basket button. 当用户单击“添加到购物篮”按钮时,它将传递photo_id和size_id。 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? 我的问题是,使用传递给控制器​​的两个ID,如何在数据透视表中访问正确的价格值?

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访问该字段

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM