数据库如果条件匹配,请选择一个常见字段



我正在构建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。

进行操作。

首先,制作一个反映您数据的模型。然后使用雄辩的查询构建器获取您要寻找的数据。如果您只需要返回一个匹配的数字,请确保添加到查询" -> distract(("。

您也可以将一系列条件传递给" Where"子句。

您的代码可能看起来像这样:

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

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

如果您只想要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();

最新更新