Iyti
Iyti

Reputation: 19

Laravel how to find multiple counts on same field of a table with a join on another table having multiple groupBy

I have two tables:

Table-1: user_invitations

user_invitations table

id user_id email
1 1 [email protected]
2 1 [email protected]

Table-2: users

users table

I want to select the following and display them in a single overview:

  1. Total number of invitation requests sent by a user.
  2. Total number of users signed up against each user's invitation by looking into the users table

No. of signups and requests

User Total Requests Total Signups
User A 5 3
User B 7 2

I have only 1 choice of using Laravel Builder Query: Illuminate\Database\Eloquent\Builder and want to fetch the statistics using a single composite query:

    return $request->withOrdering($request->withFilters(
        return query->select('user_id', DB::raw('count(*) as requests'))
        ->orWhere(function ($q) {
            return $q->select('user_id', DB::raw('count(*) as signups'))
                ->join('users', 'user_invitations.email', '=', 'users.email')
                ->groupBy('user_id');
        })
        ->groupBy('user_id')
    );

In the end, it only shows the total number of requests. The result from the query inside the orWhere(closure()) is not displaying.

Please let me suggest how the change the query but not using Model:: itself only through the Builder $query being the only choice.

Upvotes: 0

Views: 47

Answers (0)

Related Questions