【问题标题】:Joining multiple tables in laravel query builder results in duplication在 laravel 查询生成器中加入多个表会导致重复
【发布时间】:2020-02-11 15:04:32
【问题描述】:

我正在尝试使用 Laravel 查询生成器来连接 2 个表。

这是我加入 2 个表的查询


  $instructors = DB::table('instructors')
                ->join('instructor_courses', 'instructors.id', '=','instructor_courses.instructor_id')
                ->where('instructor_courses.course_id', $schedule->course_id)
                ->where('instructor_courses.position', 'Instructor')
                ->whereNull('instructor_courses.deleted_at')
                ->whereNull('instructors.deleted_at')
                ->get();

代码让我可以正确加入表格,但这会导致多次重复。看看select标签传入的结果

这是我的架构

教师表

讲师课程表

基本上我想要实现的是显示一条不重复的记录。有没有更好的方法来加入像这样的多个表?谢谢

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    您应该使用groupBy 代替instructors.id

     $instructors = DB::table('instructors')
                ->join('instructor_courses', 'instructors.id', '=','instructor_courses.instructor_id')
                ->where('instructor_courses.course_id', $schedule->course_id)
                ->where('instructor_courses.position', 'Instructor')
                ->whereNull('instructor_courses.deleted_at')
                ->whereNull('instructors.deleted_at')
                ->groupBy('instructors.id') //add a line
                ->get();
    

    【讨论】:

    • 我会按方法尝试分组
    【解决方案2】:

    尽量使用laravel中的->distinct()函数,防止选择数据出现重复。

    $instructors = DB::table('instructors')
                ->join('instructor_courses', 'instructors.id', '=','instructor_courses.instructor_id')
                ->where('instructor_courses.course_id', $schedule->course_id)
                ->where('instructor_courses.position', 'Instructor')
                ->whereNull('instructor_courses.deleted_at')
                ->whereNull('instructors.deleted_at')
                ->groupBy('instructors.id')
                ->distinct()
                ->get();
    

    【讨论】:

    • 这是错误的,它们不是重复的,这只是一对多的关系,这意味着他只需按照上述答案分组
    猜你喜欢
    • 1970-01-01
    • 2018-06-26
    • 2019-08-26
    • 2013-08-07
    • 1970-01-01
    • 2019-07-21
    • 2016-10-07
    • 2017-08-13
    • 1970-01-01
    相关资源
    最近更新 更多