Laravel雄辩:使用内部嵌套where条件

问题描述 投票:0回答:1

我正在尝试使用内部嵌套where条件。下面是我的代码

    $all = $request->all();
    $User_query = EmpProject::withCount(['exported','completed','total']);
    if($all['showSapExport'] == 'true') {
        $User_query->where('is_sap_export_list',1);
    } else {
        $User_query->where(function($q){
            $q->where('is_sap_export_list',1)
                ->orWhere(function($qIn) {
                    $qIn->orWhere('is_sap_export_list',0)->having(DB::raw('total_count'),'>',DB::raw('completed_count'));
                });
        });
    }
    dd($User_query->toSql());

我将其打印到Sql上,并且得到了它,我看不到我的条件或我雄辩的位置

SELECT `emp_projects`.*,
(SELECT COUNT(*) FROM `time_sheets`
WHERE `emp_projects`.`id` = `time_sheets`.`emp_project_id` AND `is_exported` = 1) AS `exported_count`,
(SELECT COUNT(*) FROM `time_sheets`
 WHERE `emp_projects`.`id` = `time_sheets`.`emp_project_id` AND `is_lastday` = 1) AS `completed_count`,
(SELECT COUNT(*)  FROM `assignment_histories`
 WHERE `emp_projects`.`google_project_id` = `assignment_histories`.`project_id`) AS `total_count`
FROM
    `emp_projects`
WHERE
    (`is_sap_export_list` = 0 OR(`is_sap_export_list` = 1))

我基本上有两个条件。

[第一个是如果$all['showSapExport'] == true,然后显示带有is_sap_export_list == 1的记录,并且它为假($all['showSapExport'] == false)。

然后我想要使用is_sap_export_list == 1is_sap_export_list == 0记录,但它们具有total_count > completed count

我附加了在orWhere条件内部具有完成此is_sap_export_list == 0 && total_count > completed_count的条件。但是看起来好像没有用。

我可以喜欢吗?如果是,那么为什么它不起作用。我在这里想要实现的目标还有其他选择吗?

mysql laravel eloquent having
1个回答
0
投票

好吧,我真的不确定您要做什么。我真的不明白您的问题或目标,但我已尽力为您提供帮助。

错误的事物

我不了解您的代码的某些部分。据我了解,您具有showSapExport选项。当它设置为true时,您只想显示汁液导出的项目,否则要获得所有导出的项目以及未导出但总计数大于完成计数的项目。我不明白这部分,很抱歉...

然后,您可以使用if方法(请参见下文),而不是使用when语句,并且不会在开始查询中使用orWhere

$qIn->orWhere('is_sap_export_list',0)
    ->having(DB::raw('total_count'),'>',DB::raw('completed_count'));

提议的解决方案

然后我只是将orWhere更改为位置,并使用了when方法(它与if语句具有相同的功能...我只是喜欢这样,这完全取决于您)。

$User_query = EmpProject::withCount(['exported','completed','total'])
->when($all['showSapExport'], function ($q) {
  $q->where('is_sap_export_list', 1)
})->when(!$all['showSapExport'], function ($q) {
  $q->having('total_count', '>', 'completed_count');
});
© www.soinside.com 2019 - 2024. All rights reserved.