简体   繁体   English

Laravel 哪里和哪里?

[英]Laravel whereIn AND whereIn?

So I am trying to display duplicate results based on two fields, they have to both match.所以我试图根据两个字段显示重复的结果,它们必须匹配。 I have an Expense model and I want to grab only the results where the date AND amount are the same, and return those results.我有一个Expense model,我只想获取dateamount相同的结果,然后返回这些结果。 For example, what I have so far:例如,我到目前为止所拥有的:

$results = Expense::where(function ($query) {
        $query->whereIn('amount', function ($q) {
            $q->select('amount')->from('expenses')->groupBy('amount')->havingRaw('count(*) > 1');
        })->whereIn('date', function ($q) {
            $q->select('date')->from('expenses')->groupBy('date')->havingRaw('count(*) > 1');
        });
    })
    ->get();

This does show me duplicate results BUT also where ONLY the amount OR date match, but I need both the amount AND the date to match.这确实向我显示了重复的结果,但也只有数量或日期匹配,但我需要数量和日期都匹配。 The below gives me the same results:下面给了我相同的结果:

Expense::whereIn('date', array_column(DB::select('select date from expenses group by date having count(*) > 1'), 'date'))
    ->whereIn('amount', array_column(DB::select('select amount from expenses group by amount having count(*) > 1'), 'amount'))
    ->get());

So, for example, in my database I have the following expenses :因此,例如,在我的数据库中,我有以下expenses

Name: Expense 1
Amount: 500
Date: 2022-04-16

Name: Expense 2
Amount: 500
Date: 2022-04-16

Name: Expense 3
Amount: 500
Date: 2022-04-15

The third expense should not be returned but it does get included in the results.第三项费用不应退还,但会包含在结果中。 Any pointers to get me in the right direction?有什么指示可以让我朝着正确的方向前进吗?

Although it's not using whereIn , as you stated in the question, you also have the possibility to group the rows by two columns.尽管它没有使用whereIn ,但正如您在问题中所述,您也可以按两列对行进行分组。
So, you can tell Eloquent to select the two columns you're interested in and also a count aggregate, then group by those two columns and ask for only the ones having count greater than 1 .因此,您可以告诉 Eloquent 到 select 您感兴趣的两列以及count聚合,然后按这两列分组并仅询问count大于1的列。

$results = Expense:select('amount','date', DB::raw('COUNT(*) as `count`'))
    ->groupBy('amount', 'date')
    ->havingRaw('COUNT(*) > 1')
    ->get();

Following the example:以下示例:

Expense 1费用 1

  • Amount: 500数量: 500
  • Date: 2022-04-16日期: 2022-04-16

Expense 2费用 2

  • Amount: 500数量: 500
  • Date: 2022-04-16日期: 2022-04-16

Expense 3费用 3

  • Amount: 500数量: 500
  • Date: 2022-04-15日期: 2022-04-15

The expected results would be:预期结果将是:

  • Amount: 500数量: 500
  • Date: 2022-04-16日期: 2022-04-16
  • Count: 2数量: 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM