我有以下原始SQL查询:
select a.id user_id, a.email_address, a.name_first, a.name_last, count(b.id) number_of_videos, sum(b.vimeo_duration) total_duration, sum(b.count_watched) total_playbacks
from users a,
videos b
where a.id = b.tutor_id
and a.email_address in ('candace_rennie@yahoo.com', 'tjm@hiltoncollege.com', 'matthewjameshenshall@gmail.com', 'nkululeko@syafunda.co.za', 'khulile@syafunda.co.za', 'nzakheni@syafunda.co.za')
group by a.id;
这可以从数据库中正确获取6行。我正在尝试将其转换为Laravel数据库查询,如下所示:
$totals = DB::table('users')
->select(DB::Raw('users.id as user_id'), 'users.email_address', 'users.name_first', 'users.name_last', DB::Raw('count(videos.id) as number_of_videos'), DB::Raw('sum(videos.vimeo_duration) as total_duration'), DB::Raw('sum(videos.count_watched) as total_playbacks'))
->join('videos', 'users.id', '=', 'videos.tutor_id')
->where('users.id', 'videos.tutor_id')
->whereIn('users.email_address', array('candace_rennie@yahoo.com', 'tjm@hiltoncollege.com', 'matthewjameshenshall@gmail.com', 'nkululeko@syafunda.co.za', 'khulile@syafunda.co.za', 'nzakheni@syafunda.co.za'))
->groupBy('users.id')
->get();
这将返回0行。有什么我想念的吗?
答案 0 :(得分:0)
即使groupBy
用户ID也不会有太大帮助,因为id是唯一的。
$aggregates = [
DB::raw('count(b.id) as number_of_videos'),
DB::raw('sum(b.vimeo_duration) as total_duration'),
DB::raw('sum(b.count_watched) as total_playbacks'),
];
$simpleSelects = ['users.email_address', users.id, 'users.name_first', 'users.name_last'];
$emails = ['candace_rennie@yahoo.com', 'tjm@hiltoncollege.com'....]
$users = Users::select(array_merge($simpleSelects, $aggregates))
->leftJoin('videos as b', function ($join) use ($emails) {
$join->on('b.tutor_id', 'a.id')
->whereIn('users.email_address', $emails);
})
->groupBy('users.id')
->get();
答案 1 :(得分:0)
尝试删除此行:
->where('users.id', 'videos.tutor_id')
答案 2 :(得分:-1)
列表项
在sql代码转换为laravel之后
DB :: select('posts.id','posts.title','posts.body')
->from('posts')
->where('posts.author_id', '=', 1)
->orderBy('posts.published_at', 'DESC')
->limit(10)
->get();