运行Eloquent连接查询时,我得到了一些意想不到的结果。使用完全相同的查询得到两个不同的结果。一个用DB :: raw()运行,第二个用Eloquent运行。
在Eloquent查询中,匹配
的用户 where squad_user.leave_time >= seasons.start_time
缺失,不会包含在结果集中。匹配
的用户 or squad_user.leave is null
将被包括在内。
这是两个查询结果的唯一区别。原始查询实际上产生了所需的结果集。
真的 让我感到困惑的是,如果我查看了Laravel和MySQL的查询日志,我在运行raw和Eloquent查询时会得到完全相同的查询。
原始查询(运行Eloquent查询时从查询日志中获取的实际查询)
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的Eloquent查询日志
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"}
关于Eloquent查询的MySQL的general_log
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的general_log
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 = ?
我很感激这里有任何指示,因为我很失落。
答案 0 :(得分:3)
where
绑定第3个参数并将其作为字符串处理,除非您不使用原始语句告诉它。 DB::raw
或whereRaw
适合您:
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.*']);
答案 1 :(得分:1)
从Laravel Verion 5.2开始,您还可以使用whereColumn
来验证两列是否相等(或将比较运算符传递给该方法):
->whereColumn('squad_user.join_time', '<=', 'seasons.end_time')