Laravel 5.4 SQL查询嵌套Where / OrWhere

时间:2017-02-26 20:00:04

标签: php mysql laravel eloquent

我有这些表

贷款表 | coop_id | loan_id | loan_availability |

贷款季节表 | coop_id | loan_id | loan_season_start | loan_season_end |

我试图将每笔贷款的详细信息放在一个数组中,无论其可用性是始终还是季节性。如果它被标记为季节性,则它在贷款季节表中有一个数据。

这是我的查询

$loanlist = DB::table('loans')
        ->join('loan_seasons', 'loan_seasons.loan_id', 'loans.loan_id')
        ->where('loans.coop_id', $coop_id)
        ->where(function ($q){ 
            $q->where('loans.loan_availability', "Always")
            ->orWhere(function ($qq){ 
                $qq->where('loans.loan_availability', "Seasonal")  
                ->where('loan_season_start', '>=', Carbon::now()->month)
                ->where('loan_season_end', '<=', Carbon::now()->month)
                ->where('loan_season_status', 1);
            });
        })
        ->where('loans.loan_status', "1")
        ->get()->toArray();

我收到了这个输出:

Array(
    [0] => Array(
        [id] => 2
        [coop_id] => 1
        [loan_id] => 3
        [loan_name] => Loan 1
        [loan_desc] => Loan 1 Description
        [loan_maxamount] => 500000
        [loan_availability] => Always
        [loan_status] => 1
        [created_at] => 2017-02-26 17:43:08
        [updated_at] => 2017-02-26 17:43:08
        [loan_season_start] => 2
        [loan_season_end] => 6
        [loan_season_status] => 1
    )
)

我的预期输出是这样的:

Array(
    [0] => Array(
        [id] => 1
        [coop_id] => 1
        [loan_id] => 3
        [loan_name] => Loan 1
        [loan_desc] => Loan 1 Description
        [loan_maxamount] => 500000
        [loan_availability] => Always
        [loan_status] => 1
        [created_at] => 2017-02-26 17:43:08
        [updated_at] => 2017-02-26 17:43:08
        [loan_season_status] => 1
    )
   [1] => Array(
        [id] => 2
        [coop_id] => 1
        [loan_id] => 4
        [loan_name] => Loan 2
        [loan_desc] => Loan 2 Description
        [loan_maxamount] => 200000
        [loan_availability] => Seasonal
        [loan_season_start] => 2
        [loan_season_end] => 6
        [loan_status] => 1
        [created_at] => 2017-02-26 17:43:08
        [updated_at] => 2017-02-26 17:43:08
        [loan_season_status] => 1
    )
)

我一直试图解决这个问题几个小时,但我仍然无法正确查询。有人可以帮忙吗?我对嵌套查询很新。帮助

1 个答案:

答案 0 :(得分:0)

我现在就开始工作了。好像我一直在简单的查询复杂。我为每个条件创建了不同的查询,并将它们合并为一个。谢谢。