我有这些表
贷款表 | coop_id |贷款编号 |贷款可用性|
贷款季节表 | coop_id |贷款编号 | loan_season_start | loan_season_end |
我正试图在一个数组中获取每笔贷款的详细信息,无论它们的可用性是Always 还是Seasonal。如果标记为季节性,则它在贷款季节表中有一个数据。
这是我的查询
$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
)
)
我已经尝试解决这个问题几个小时了,但我仍然无法正确查询。有人可以帮忙吗?我对嵌套查询很陌生。帮忙?
最佳答案
我现在开始工作了。好像我一直在使简单的查询变得复杂。我为每个条件创建了不同的查询,并将它们合并为一个。谢谢。
关于php - Laravel 5.4 SQL 查询嵌套 Where/OrWhere,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42473533/