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条)

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?