【问题标题】:Convert Raw SQL query to Laravel DB Query将原始 SQL 查询转换为 Laravel DB 查询
【发布时间】:2019-02-03 20:54:02
【问题描述】:

我有以下原始 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 行。有什么我想念的吗?

【问题讨论】:

  • 还可以尝试在 groupby 子句中添加 email_address、first_name、last_name。
  • 您是否为这些表设置了模型?

标签: mysql sql laravel eloquent


【解决方案1】:

尝试删除此行:

->where('users.id', 'videos.tutor_id')

【讨论】:

    【解决方案2】:
    1. 列表项

      sql代码转换成laravel后

    2. DB::select('posts.id','posts.title','posts.body')

                                         ->from('posts')
                                      ->where('posts.author_id', '=', 1)
                                      ->orderBy('posts.published_at', 'DESC')
                                      ->limit(10)
                                      ->get();
      

    【讨论】:

    • 你能解释一下你想在这里做什么吗?
    【解决方案3】:

    它应该像下面这样,即使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();
    

    【讨论】:

      猜你喜欢
      • 2020-10-19
      • 2017-01-05
      • 2015-06-26
      • 2019-05-31
      • 2023-01-14
      • 2019-04-29
      • 2021-08-19
      • 2019-04-04
      • 2011-11-09
      相关资源
      最近更新 更多