2017-02-26 66 views
2

我有這些表Laravel 5.4 SQL查詢嵌套在哪裏/ OrWhere

貸款表 | 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 
    ) 
) 

我一直在試圖解決這幾個小時,但我仍然無法得到正確的查詢。有人可以幫忙嗎?我對嵌套查詢很陌生。幫幫我?

回答

0

我現在工作了。似乎我一直在簡單的查詢複雜。我爲每個條件創建了不同的查詢,並將它們合併爲一個。謝謝。