2016-04-03 124 views
3

我在Laravel雄辯中遇到了一個問題,當我運行查詢並且生成的查詢似乎不是我期望的結果時,我得不到結果。高級Where子句在Laravel

這是在控制器代碼:

$lastUpdate = Input::get('last_update'); 
$userId = Auth::user()->id; 

$eventIds = EventVendor::where('user_id', $userId) 
        ->where('is_active', 1)->get()->lists('event_id'); 

$events = EventDetails::whereIn('id', $eventIds) 
        ->where(function($query) use ($lastUpdate) { 
         $query->where('created_at', $lastUpdate); 
         $query->orWhere('updated_at', $lastUpdate); 
        }) 
        ->where('is_active', 1) 
        ->with("details_sub") 
        ->with("extras") 
        ->with("chargesDiscounts") 
        ->toSql(); 

這是生成的查詢:

select * from `mtgh_event_details` 
    where `mtgh_event_details`.`deleted_at` is null 
     and 0 = 1 
     and (`created_at` = ? or `updated_at` = ?) 
     and `is_active` = ? 

除了這是不應該在那裏我看不到0 = 1完整的查詢要麼。

+0

「0 = 1」是否實際顯示在您的查詢中,或者是您爲該問題更改了哪些內容? – patricus

+0

它顯示在我的查詢中。 – user3718908

回答

1

所以我找到了問題,查詢

$eventIds = EventVendor::where('user_id', $userId) 
        ->where('is_active', 1)->get()->lists('event_id'); 

現在回來null或空列表顯然這一部分,因此0 = 1我的查詢。另外在另一個答案的幫助下,我能夠簡化我的代碼,謝謝。 :)

3

0 = 1正在顯示,因爲填充您的$eventIds的查詢未返回任何結果,因此您的Collection爲空。如果將空數組(或Collection)傳遞給whereIn(),則它通過在0 = 1中添加快捷方式查詢,因爲搜索where id in()是無效的SQL,並且在空集合中進行邏輯搜索將總是返回無結果。這個快捷方式在4.2.17中添加了this pull request

至於查詢的其餘部分,一切看起來都正常。 with()語句正在設置預加載,它使用單獨的SQL語句;它不使用連接。

所以,既然你有三個with()語句,你實際上將運行4個單獨的查詢,一個讓你EventDetails,然後每一個加載您details_subextraschargesDiscounts用於加載的事件細節。

由於它們是單獨的查詢,它們不會顯示在toSql()輸出中。


其他說明:

  • 當獲得的事件ID,你並不需要調用->get()->lists(),你可以簡單地調用查詢->lists()。如果您首先撥打get(),它會將全部對象加載到Collection中,然後您在Collection上調用lists()。您可以通過在查詢本身上調用lists()來避免首先加載完整的Collection

  • 假設你有關係設置,你可以避免最初的查詢來獲取ID。您可以改用whereHas() method。您的查詢將如下所示:

    $lastUpdate = Input::get('last_update'); 
    $userId = Auth::user()->id; 
    
    // assumes a relationship named 'vendor' 
    $events = EventDetails::whereHas('vendor', function($query) use ($userId) { 
          // $query is query for the EventVendors 
          $query->where('user_id', $userId)->where('is_active', 1) 
         }) 
         ->where(function($query) use ($lastUpdate) { 
          $query->where('created_at', $lastUpdate); 
          $query->orWhere('updated_at', $lastUpdate); 
         }) 
         ->where('is_active', 1) 
         ->with("details_sub") 
         ->with("extras") 
         ->with("chargesDiscounts") 
         ->toSql(); 
    
+0

user3718908我已更新我的答案,以提供有關您的0 = 1問題的一些信息。 – patricus