[英]Getting a specific column value from a pivot table
我有三个桌子, 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
显示上面的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`
)
在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;
另外,请确保使用->withPivot
:
public function products()
{
return $this->belongsToMany('App\Product')->withPivot('price');;
}
在您的Product
型号中定义此项
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.