Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

laravel query builder count relationship

I am stuck with a query builder in laravel 8

DB::table('users')
    ->join('contracts', 'users.id', '=', 'contracts.user_id')
    ->join('roles', 'roles.id', '=', 'users.role_id')
    ->select('users.id', 'users.username', 'users.email', DB::raw('COUNT(contracts.user_id) as numberOfContracts'))
    ->groupBy('users.id')
    ->paginate(10);

i am getting only 80 of total entries …. and I have 103 users.

I want to display all the users with paginate of course….. and show for each user the role and how many contracts have.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What I did wrong ?

*** UPDATE ***

the tables are these:

users (id, username, email, role_id)

contracts (id, name, user_id)

roles (id, name)

*** update 2 ***

If run the eloquent

User::with('contracts', 'role')
->withCount('contracts')
->paginate(10);

it return all the 103 with count. But how to do it with query builder ?

>Solution :

You were using straight JOIN (which equated to an INNER JOIN since that’s what MySQL defaults to) in Laravel Query Builder. It will not account for Empty contracts, or roles. You need a LEFT JOIN to do this.

DB::table('users')
    ->leftJoin('contracts', 'users.id', '=', 'contracts.user_id')
    ->leftJoin('roles', 'roles.id', '=', 'users.role_id')
    ->select('users.id', 'users.username', 'users.email', DB::raw('COUNT(contracts.user_id) as numberOfContracts'))
    ->groupBy('users.id')
    ->paginate(10);

See This SO Question to see the difference in JOINSDifference in MySQL JOIN vs LEFT JOIN

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading