1

i have the following query

select * from (SELECT accident.id,count(*) as cnt from accident left join driver on driver.accident_id = accident.id group by accident.id)alias where cnt = 1

and this is my query builder

$accidents = DB::table('accident')
        ->leftjoin('driver','accident.id','driver.accident_id')
        ->select(DB::raw('accident.*,count(*) as jumlah_kendaraan'))->groupBy('accident.id')
        ->where('jumlah_kendaraan', $jumlah_kendaraan);

i tried to convert it like the above but i got an error says

SQLSTATE[42703]: Undefined column: 7 ERROR: column "jumlah_kendaraan" does not exist

can anyone help me to solve it? thanks in advance

2 Answers 2

1

You cannot filter the result of an aggregate function count() using where clause, Instead use having for this purpose

->having('jumlah_kendaraan', $jumlah_kendaraan) 

Or use your complete expression

->havingRaw('count(*) = '.$jumlah_kendaraan)
Sign up to request clarification or add additional context in comments.

2 Comments

i replace where with having but i still got the same error sir
@PinballWizard I have added another clause, Are you sure you got the same error or different error ?
1

where clause can not use alias of group function directly, use

->where('count(*)', $jumlah_kendaraan);

You can use having as well but in case if having is not working use like given above.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.