【问题标题】:Database select one common field if conditions match如果条件匹配,数据库选择一个公共字段
【发布时间】:2017-05-30 22:59:47
【问题描述】:

我正在构建 Laravel 5.4 Web 应用程序,并且我有以下数据库表:

==================================
product_id|attribute_id|option_id
==================================
1         | 1          | 1
1         | 2          | 3
1         | 4          | 10
2         | 1          | 1
2         | 2          | 4
... etc

所以我提交带有属性 id 和选项 id 的表单,这样我就可以从中构建数组或其他任何东西。

我想要实现的是我从数据库中选择与精确组合匹配的 product_id,例如:

[
attribute_id => 1,
option_id => 1

attribute_id => 2,
option_id => 3

attribute_id => 4,
option_id => 10
]

此条件仅适用于 product_id = 1 的产品

不知道我是否可以使用数据库查询或通过 php 来做到这一点。

【问题讨论】:

  • 你想要的和你的例子一样吗?
  • @MahmoudMustafa,如果我的回答是正确的,请把它标记为这样,以便其他人可以快速找到它。

标签: php mysql database laravel laravel-5.3


【解决方案1】:

首先,制作一个能够反映您的数据的模型。然后使用 Eloquent 查询构建器获取您要查找的数据。如果您只需要返回一个匹配的数字,请确保在查询末尾添加“->distinct()”。

您还可以将一组条件传递给“where”子句。

您的代码可能如下所示:

$match = DB::table('products')
                ->where('attribute_id', 1)
                ->where('option_id', 1)
                ->distinct()
                ->get();

https://laravel.com/docs/5.4/queries#introduction

【讨论】:

    【解决方案2】:

    如果您只想要 product_id = 1 的产品 假设您已将其存储在“product_attribute_option”表中 其字段为 product_id |attribute_id | option_id 如您所见。

          $query = DB::table('product_attribute_option as pao');
          $query->where('pao.product_id', 1);
          $results = $query->get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-21
      • 1970-01-01
      • 2011-03-18
      • 1970-01-01
      • 1970-01-01
      • 2020-01-04
      相关资源
      最近更新 更多