php 如何获取表中单一字段_PHP-从数据透视表中获取特定的列值

问题

我有三个表,商店,产品和product_shop作为数据透视表.商店和产品通过一个belongsToMany(多对多)进行关联.在将新产品插入数据库时​​,可以在我的表格中为每个商店指定价格.提交表单时,会将product_id和shop_id及其相关价格插入到Pivot表中.

我的问题是,当指定shop_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_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`

)

理想的最终结果(包括从数据透视表中收集的价格):

6Lddw.png

解决方法:

在您的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;

标签:laravel,mysql,php

来源: https://codeday.me/bug/20191111/2022307.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值