Laravel 加入和不同

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45362846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:23:42  来源:igfitidea点击:

Laravel join and distinct

phplaraveleloquent

提问by wpgeek

In Laravel, I have a query which is:

在 Laravel 中,我有一个查询:

$productsModel->join('tags', 'tags.item_id', '=', 'products.id')
      ->select('products.*', 'tags.item_id')
      ->distinct();

DB tables looks like this:
| products | tags    |
 ----------|---------|
| id       | id      |
|          | item_id |

products has a one to many relationship with tags, which creates issues when joining tables. As an example, I need to query products based on multiple tags, but I need to show only one product.

产品与标签之间存在一对多关系,这会在连接表时产生问题。例如,我需要根据多个标签查询产品,但我只需要显示一个产品。

回答by fubar

Okay. You're going to have to provide a little more context.

好的。您将不得不提供更多背景信息。

From the looks of things, you have a 1:n relationship, where TableA has many TableB. Therefore, if you do a join, you may have multiple TableB records joined to TableA records, which is fine.

从表面上看,你有一个 1:n 的关系,其中 TableA 有很多 TableB。因此,如果您进行连接,您可能有多个 TableB 记录连接到 TableA 记录,这很好。

But then, if you want to select a distinct TableA record, which of the many possible TableB records should be returned, if there's more than one?

但是,如果您想选择一个不同的 TableA 记录,如果有多个可能的 TableB 记录,应该返回哪一个?

An easy way to achieve what you're asking is to use GROUP BY.

实现您所要求的一种简单方法是使用GROUP BY.

$tableA->selectRaw('table_a.*, MAX(table_b.item_id) AS item_id')
    ->join('table_b', 'table_a.id', '=', 'table_b.item_id')
    ->groupBy('table_a.id')
    ->get();

It's also worth mentioning that selecting table_b.item_idisn't necessary, because the value will always equal table_a.id. Just saying.

还值得一提的是,选择table_b.item_id不是必需的,因为值将始终等于table_a.id。就是说。

Edit- based on your updated question, if you just want to find products with specific tags, you can use WHERE INand just not select a field from table_b.

编辑- 根据您更新的问题,如果您只想查找带有特定标签的产品,您可以使用WHERE IN而不是从table_b.

$tableA->select('table_a.*')
    ->join('table_b', 'table_a.id', '=', 'table_b.item_id')
    ->whereIn('table_b.id', [1, 2, 3])
    ->groupBy('table_a.id')
    ->get();

回答by pady

$tableA->select('table_a.id')
->join('table_b', 'table_a.id', '=', 'table_b.item_id')
->whereIn('table_b.id', [1, 2, 3])
->groupBy('table_a.id')
->get();

Select only that column which you want to group by.

仅选择您要作为分组依据的那一列。