问题
我有三个表,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 中使用该集合,这样我就不必在我的 View 中使用特定方法。所以基本上我需要的是类似这样的东西:
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`
)
理想的最终结果(包括从数据透视表中收集的价格):
最佳答案
在您的 product.php(模型)文件中定义此关系
public function priceCol($shopId)
{
return $this->belongsTo(ProductShop::class,'product_id')->where('shop_id',$shopId);
}
用于检索特定产品的价格
$product = Product::find(1);
$price = $product->priceCol($shopId)->price;
关于php - 从数据透视表中获取特定列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41908440/