This is my query
Student::query()
->addSelect(['presentCount' =>
Score::query()
->selectRaw('count(*)')
->whereColumn('student_id', '=', 'students.id')
->where('created_at', '>', getBeginningOfThisYear())
->where('presence', '=', 1)
])->where('presentCount', '>=', 5)->get()
the raw SQL is
select "students".*, (select count(*) from "scores" where "student_id" = "students"."id" and "created_at" > ? and "presence" = ? and "scores"."deleted_at" is null) as "presentCount" from "students" where "presentCount" >= ? and "students"."deleted_at" is null
the problem is presentCount is an alias and it can not be used in where clause, however if I can change the SQL to be like:
select * from (select "students".*, (select count(*) from "scores" where "student_id" = "students"."id" and "created_at" > ? and "presence" = ? and "scores"."deleted_at" is null) as "presentCount" from "students" ) as students where "students"."presentCount" >= ? and "students"."deleted_at" is null
The question is how can I transform the query using query builder not raw SQL?