2014-07-08 49 views
2

運行Eloquent聯接查詢時收到一些意外的結果。我使用完全相同的查詢得到兩個不同的結果。一個使用DB :: raw()運行,另一個使用Eloquent。使用與DB :: raw和Eloquent相同的查詢的不同結果

在雄辯查詢相匹配的

where squad_user.leave_time >= seasons.start_time

失蹤,將不包括在結果集中的用戶。該

​​

相匹配的用戶將被納入然而,。

這是兩個查詢結果的唯一區別。原始查詢實際上會生成所需的結果集。

什麼真正困惑我的是,如果我檢查查詢日誌,既Laravel的和MySQL,我同時運行原料和雄辯的查詢時,得到完全相同的查詢。

原始查詢(在實際查詢運行雄辯查詢時,我從查詢日誌中獲得)

return \DB::select(\DB::raw(' 
     select users.* 
     from users 
     inner join squad_user on users.id = squad_user.user_id 
     inner join seasons on squad_user.squad_id = seasons.squad_id 
     where squad_user.join_time <= seasons.end_time 
     and (squad_user.leave_time >= seasons.start_time or squad_user.leave_time is null) 
     and seasons.id = :seasonId 
    '), 
    ['seasonId' => 3] 
); 

雄辯查詢

return User::join('squad_user', 'users.id', '=', 'squad_user.user_id') 
      ->join('seasons', 'squad_user.squad_id', '=', 'seasons.squad_id') 
      ->where('squad_user.join_time', '<=', 'seasons.end_time') 
      ->where(function ($query) 
      { 
       $query->where('squad_user.leave_time', '>=', 'seasons.start_time') 
        ->orWhereNull('squad_user.leave_time'); 
      }) 
      ->where('seasons.id', 3) 
      ->get(['users.*']); 

Laravel雄辯的查詢日誌

select `users`.* 
from `users` 
inner join `squad_user` on `users`.`id` = `squad_user`.`user_id` 
inner join `seasons` on `squad_user`.`squad_id` = `seasons`.`squad_id` 
where `squad_user`.`join_time` <= seasons.end_time 
and (`squad_user`.`leave_time` >= seasons.start_time or `squad_user`.`leave_time` is null) 
and `seasons`.`id` = 3 
{"bindings":["seasons.end_time","seasons.start_time",3],"time":0.38,"name":"mysql"} 

MySQL的上雄辯查詢

select `users`.* 
from `users` 
inner join `squad_user` on `users`.`id` = `squad_user`.`user_id` 
inner join `seasons` on `squad_user`.`squad_id` = `seasons`.`squad_id` 
where `squad_user`.`join_time` <= ? 
and (`squad_user`.`leave_time` >= ? or `squad_user`.`leave_time` is null) 
and `seasons`.`id` = ? 

MySQL的對原始查詢

select users.* 
      from users 
      inner join squad_user on users.id = squad_user.user_id 
      inner join seasons on squad_user.squad_id = seasons.squad_id 
      where squad_user.join_time <= seasons.end_time 
      and (squad_user.leave_time >= seasons.start_time or squad_user.leave_time is null) 
      and seasons.id = ? 

我會在這裏欣賞任何指針,因爲我很失落general_log general_log。

回答

2

where綁定第三個參數並將其視爲一個字符串,除非您通過使用原始語句告訴它不要。 DB::rawwhereRaw將爲你工作:

return User::join('squad_user', 'users.id', '=', 'squad_user.user_id') 
     ->join('seasons', 'squad_user.squad_id', '=', 'seasons.squad_id') 
     ->where('squad_user.join_time', '<=', DB::raw('seasons.end_time')) 
     ->where(function ($query) 
     { 
      $query->where('squad_user.leave_time', '>=', DB::raw('seasons.start_time')) 
       ->orWhereNull('squad_user.leave_time'); 
     }) 
     ->where('seasons.id', 3) 
     ->get(['users.*']); 
+0

非常好,非常感謝。不能相信我沒有發現綁定的區別。 – nielsiano

相關問題