Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

berkkaya's avatar

How to do this query in Laravel Query Builder

Hi guys, I have tried to implement this query on query builder but I failed.

select *, (SELECT avg(score) FROM scores where application_id = A.id) as score from application_forms as A inner join users as B on A.user_id = B.id

This is what I tried but I cant add scores table :)

DB::table('application_forms as A') ->join('users as B', 'A.user_id', '=', 'B.id') ->select( '*' );

0 likes
8 replies
Qlic's avatar
DB::table('application_forms')->join('users', 'application_forms.user_id', '=', 'users.id')->select('users.*', 'application_forms.*')->selectRaw(DB::raw("AVG(application_forms.score) AS avg_score"))->get();
1 like
berkkaya's avatar

@Qlic Score is not on the application_forms its on different table (scores) and it can be returned null.

I have 3 different tables. users, application_forms, scores

Foreign Keys: scores.application_id = application_forms.id application_forms.user_id = users.id

Also I dont want to have duplicate score data.

I just want to see averages of scores. (If no score it should return 0)

Qlic's avatar

Ahh oke, than this should be it.

DB::table('application_forms')->join('users', 'application_forms.user_id', '=', 'users.id')
->leftJoin('scores', 'application_forms.id', '=', 'scores.application_id')
->select('users.*', 'application_forms.*')
->selectRaw(DB::raw("COALESCE(AVG(scores.score), 0) AS avg_score"))
->get();

You can add additional groupBy clause to prevent possible duplicates.

berkkaya's avatar

@Qlic

This is the error that I am getting now :)

SQLSTATE[42000]: Syntax error or access violation: 1140 In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column 'finansbank.users.id'; this is incompatible with sql_mode=only_full_group_by (SQL: select users., application_forms., COALESCE(AVG(scores.score), 0) AS avg_score from application_forms inner join users on application_forms.user_id = users.id left join scores on application_forms.id = scores.application_id)

Qlic's avatar

Is it save to drive a car, no, still people do it. Personally i see no harm in doing so, i've done it in my own projects aswell.

But if you don't, you'll have to use a groupBy, apparently on the users.id field.

jlrdw's avatar

Why do you guys use >selectRaw(DB::raw(.. when you could just use getPdo() and be done.

Please or to participate in this conversation.