一个包含超过 3000 个元素的 whereIn 子句的 eloquent 查询有效,但另一个具有相同元素和格式的查询无效

One eloquent query with whereIn clause with more than 3000 elements works but another one with the same elements and format doesn't

您好,在此先感谢您的帮助。 几天来我一直在为这个问题碰壁,所以决定在这里问问。我在 Laravel 中有两个查询,一个按周分组总计,另一个按月分组。第一周工作正常但由于某种原因一个月没有,本质上查询的唯一区别是每周一次是每年计算一次但在不同的时期(从去年的第 48 周开始到去年的第 47 周结束)今年),而月度就是真实的年份。唯一的区别是周查询在 if 中,以显示一年中最后几周的正确 thata。

$weeklySalesLastYear = Invoice::where(function ($query) use ($year, $client_ids){
            $query->where('year', $year-2)->where('week', '>=', 48)->whereIn('client_id', $client_ids);
        })->orWhere(function($query) use ($year, $client_ids){
            $query->where('year', $year-1)->where('week', '<=', 47)->whereIn('client_id', $client_ids);
        })->groupBy('week')->selectRaw('sum(total) as total, week')->get();

这是我的每周查询,效果很好。

$sortedMonthlySalesLastYear = DB::table('invoices')
        ->where('year', $year-1)->whereIn('client_id', $client_ids)
        ->groupBy('month')->selectRaw('sum(total) as total, month')->get();

这是我的每月查询,但没有用。我知道 eloquent 中的 whereIn 子句存在问题,由于某种原因它们不接受大量元素,但我想知道为什么一个有效而另一个无效,以及是否有解决方案给它。我也希望它是一个对象,我试过使用原始查询但它抛出一个数组,我宁愿避免使用它。这是有效的。

$sortedMonthlySalesLastYear = DB::select( DB::raw("SELECT SUM(total) AS total, month FROM invoices WHERE year = '$lastYear' AND client_id IN ($client_ids_query) GROUP BY month"))

Schema::create('invoices', function (Blueprint $table) {
        $table->id();
        $table->string('month');
        $table->integer('year');
        $table->integer('week');
        $table->integer('client_id')->index()->unsigned();
        $table->integer('product_id')->index()->unsigned();
        $table->integer('quantity');
        $table->float('total');
        $table->double('discount');
    });

这就是我的发票迁移的样子,客户端与用户相关,这就是我获取数组的方式。

每月查询是这样的returns:

[2022-05-02 23:40:05] local.INFO: monthly sales:  
[2022-05-02 23:40:05] local.INFO: []  

这就是每周一次 returns(这是一个更大的集合 但这是它展示其工作原理的示例。)

[2022-05-02 23:42:42] local.INFO: weekly sales: 
[2022-05-02 23:42:42] local.INFO: 
[{"total":536190.4699999997,"week":1}, 
 {"total":568192.6700000003,"week":2}, 
 {"total":1613808.48,"week":3},
 {"total":878447.3600000001,"week":4}...]

我尝试处理的几张发票的示例如下(数据库中有超过 13 万张发票):

我将不胜感激任何帮助,如果您对此有解决方案,我主要更愿意继续使用 eloquent 以使代码看起来更清晰。谢谢。

我还必须补充一点,如果我与任何其他用户一起登录,查询 returns 预期值,因为他们拥有的客户范围要小得多。

我想了这么久。我唯一做的就是内爆 client_ids 集合,然后将其分解成一个数组。不知道为什么它接受一个大数组而不是一个大集合,仍然不知道查询之间的差异。

$clients = Client::where('user_id', $user_id)->get('id');
$imp = $clients->implode('id', ', ');
$client_ids = explode(', ', $imp);

所有查询都适用。