Php 从数据透视表获取特定列值 问题

Php 从数据透视表获取特定列值 问题,php,mysql,laravel,Php,Mysql,Laravel,我有三个表,shops,products,和product\u shop作为数据透视表。商店和产品使用目录(多对多)进行关联。将新的产品插入数据库时,我可以在表格中为每个商店指定价格。提交表单时,产品标识和店铺标识将与其相关价格一起插入透视表 我的问题是,在指定shop\u id时,如何仅从透视表中检索产品的价格?最终,我的目标如下所述,可能有更好的解决方案 解释 此外,我为什么需要这个是以下。我还有一个类别表。在我的索引视图中我想做这样的事情: @foreach($categories as

我有三个表,
shops
products
,和
product\u shop
作为数据透视表。
商店
产品
使用
目录
(多对多)进行关联。将新的
产品
插入数据库时,我可以在表格中为每个
商店
指定价格。提交表单时,
产品标识
店铺标识
将与其相关价格一起插入透视表

我的问题是,在指定
shop\u id
时,如何仅从透视表中检索产品的价格?最终,我的目标如下所述,可能有更好的解决方案

解释 此外,我为什么需要这个是以下。我还有一个
类别
表。在我的
索引视图中
我想做这样的事情:

@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\u 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
数据库表 理想的最终结果(包括从数据透视表收集的价格): 在product.php(Model)文件中定义此关系

public function priceCol($shopId)
{
  return $this->belongsTo(ProductShop::class,'product_id')->where('shop_id',$shopId);
}
用于检索特定产品的价格

$product = Product::find(1);
$price = $product->priceCol($shopId)->price;
使用雄辩的语言:

$shop=Shop::where('id',$id)->first();
$shop->pivot->price;
此外,请确保在以下方面使用
->with pivot

public function products()
{
    return $this->belongsToMany('App\Product')->withPivot('price');;
}

在您的
产品
模型中定义此

public function shops () {
    return $this->belongsToMany(Shop::class)->wirhPivot('price'); 
}
那你可以

Product::with('shops')->get();

很遗憾,由于上面所有的答案都不是我想要的100%,因此,我最终会将价格计算出来

public function price($shop_id)
{
    return $this->shops()->where('shop_id', $shop_id)->first()->pivot->price;
}

也许这就是我想要的:)
public function price($shop_id)
{
    return $this->shops()->where('shop_id', $shop_id)->first()->pivot->price;
}