In this small article. i will let you know how to use select with count aggregate and group by using db raw in Laravel application. Here i gave you simple query example for join with count(*) as aggregate in select statement, i convert it into laravel db query builder.
If you want to use count aggregate function in select statement then you require to use db::raw in eloquent select function in Laravel 5 application. If you write query in SQL then it is very easy to write as like bellow:
users.id, users.name, COUNT(click.*) as count_click
INNER JOIN click ON click.user_id = users.id
GROUP BY users.id
As we write above sql query, we have to convert it into laravel db query. It's not any default provided query in laravel. But we can use it by using DB::raw. So let's see bellow example.
$data = DB::table("users")
->select("users.id", "users.name", DB::raw("COUNT(click.*) as count_click"))
As you can see above, i convert sql into db raw query as like above.
I hope you found your best solution....
Do you like below Tutorials ?
- How to Check Multiple Checkbox in Angular?
- Laravel Create File Object from Path Example
- PHP Check If String Contains HTML Tags Example
- Find URL in String and Make Link in PHP Example
- Jquery Textarea Auto Increase Height Example
- Laravel Create PDF with Charts Example
- Laravel Add Image to PDF File Example