【发布时间】:2017-01-28 09:54:08
【问题描述】:
问题
我有三个表,shops、products 和 product_shop 作为数据透视表。 Shop 和 Product 使用 belongsToMany(多对多)关联。在数据库中插入一个新的Product 时,我可以在我的表单中为每个Shop 指定一个价格。提交表单时,product_id 和 shop_id's 将插入数据透视表及其相关价格。
我的问题是,当指定shop_id 时,如何仅从数据透视表中检索产品的价格?最终,我的目标如下所述,并且可能有更好的解决方案。
说明
此外,我需要它的原因如下。我也有一个categories 表。在我的index view 中,我想做这样的事情:
@foreach($categories as $category) // All categories
{{ $category->name }} // Display the name of the category
@foreach($category->products as $product) // Loop through all related products for each category
{{ $product->name }}
{{ $product->price }}
@endforeach
@endforeach
现在的诀窍是价格来自数据透视表。我想根据shop_id 显示以上内容。理想情况下,我只想创建一个查询,在其中选择我需要的所有内容,然后在我的 foreach 中使用该集合,因此我不必在我的视图中使用特定方法。所以基本上我需要的是这样的东西:
select
categories->with('products') // Select all categories while eager loading the products
price // Collected from the pivot table where the shop_id is equal to the given shop_id
数据库表
CREATE TABLE `categories` (
`id`,
`user_id`,
`name`,
`created_at`,
`updated_at`
)
CREATE TABLE `shops` (
`id`,
`user_id`,
`name`,
`created_at`,
`updated_at`
)
CREATE TABLE `products` (
`id`,
`user_id`,
`category_id`,
`name`,
`created_at`,
`updated_at`
)
CREATE TABLE `product_shop` (
`id`,
`product_id`,
`shop_id`,
`price`,
`created_at`,
`updated_at`
)
理想的最终结果(包括从数据透视表中收集的价格):
【问题讨论】: