Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

php - Laravel - How to write two inner joins with a count statement in Laravel syntax?

I have three tables:

  1. Users (columns id, dept_id)
  2. Departments (columns id, deptStringName)
  3. Absences (columns id, user_id)

I am trying to figure out Absences per Department. I know I need two inner joins, but at the moment I am confused about how to insert a count in two inner joins using the Laravel Query Builder syntax.

The eventual result could be like:

+-------+---+
| DeptA | 3 |
| DeptF | 7 |
| DeptH | 3 |
| DeptT | 7 |
| DeptZ | 5 |
+-------+---+

EDIT: I don't mind the SQL syntax either.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So basically something like the following should work:

DB::table('departments')
    ->join('users','users.dept_id','=','departments.id')
    ->join('absences','users.id','=','absences.user_id')
    ->select('departments.id','departments.deptStringName', DB::raw("COUNT(*)"))
    ->groupBy('departments.id','departments.deptStringName')
    ->get();

Note: When grouping by you should group by the unique values of the row (e.g. the identifier). If your department names are guaranteed to be unique then you can omit selecting and grouping by department.id completely.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...