php - 从数据透视表中获取特定列值

标签 php mysql laravel

问题

我有三个表,shopsproductsproduct_shop 作为数据透视表。 ShopProduct 使用 belongsToMany(多对多)关联。将新的 Product 插入数据库时​​,我可以在我的表单中为每个 Shop 指定价格。提交表单时,product_idshop_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`
)

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

with the price entered

最佳答案

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

相关文章:

php - 在 MySql 中将 2 行计数加在一起

php - 服务器上的 500 内部服务器错误,但在开发系统上工作

php - 具有多个表的 Symfony sfDoctrinePager

php - 在一页上测试两个表单 `press` 指令总是提交第二个表单

javascript - JS SDK facebook API 通行证

php - 比较当前日期之前和之后的数据集

php - 从 CS 购物车的网站搜索中排除类别

mysql - Mongify - SQL 连接和 mongo 连接不起作用

php - Laravel 保护 Amazon s3 存储桶文件

php - CakePHP 3.0 中的分页