duangeli1334 2018-07-24 18:11
浏览 83
已采纳

使用laravel连接查询

I'm really getting confused with the join on laravel.

I got a users table and got a students_subjects table, in the students_subjects table I got a subject_id column and a user_id column, I'm trying to get the users list by the user_id at the teachers_subjects table with the same subject_id column at the students_subjects.

I've tried :

$user_id = Auth::user()->id;
$results = DB::table('users')
->join('students_subjects', 'students_subjects.subject_id', '=', 'teachers_subjects.subject_id')
->where('students_subjects.user_id', $user_id)
->get();

but I got some errors... would be great if someone can show me the way it should be done so I can understand how to do the joins work at laravel.

structures:

users table :
- id
- name
- last name

students_subjects :
- subject_id
- user_id (users->id)

teachers_subjects :
- subject_id
- teacher_id (users->id)
  • 写回答

2条回答 默认 最新

  • doujiu8918 2018-07-24 18:18
    关注

    You need to add a join for both tables:

    $user_id = Auth::user()->id;
    $results = DB::table('users')
    ->join('students_subjects', 'users.id', '=', 'students_subjects.user_id')
    ->join('teachers_subjects', 'students_subjects.subject_id', '=', 'teachers_subjects.subject_id')
    ->where('students_subjects.user_id', $user_id)
    ->get();
    

    You may have to tweak this to get exactly what you're looking for.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答