I am trying to create a Laravel statement which should return the correct values per user for amount of answers and amount of questions like so:
$users = User::join('user_answers', 'users.id', '=', 'users_answers.user_id')
->join('user_questions', 'users.id', '=', 'user_questions.user_id')
->select(
'users.id',
'users.username',
DB::raw('COUNT(user_answers.user_id) AS answers'),
DB::raw('COUNT(user_questions.user_id) AS questions')
)
->groupBy('users.id');
NOTE: The groupBy is required for it to work because it is used in DataTables, otherwise it will show only one row.
When I attempted to:
dd($users->first());
What I got is this:
As you can see, the values are for some reason the same for questions and answers, and are incorrect. I imagine there is some kind of overlapping with the joins.
For instance, if I remove one of the joins, and leave one of the columns only, the numbers show correctly, like so:
I am honestly quite lost here, would appreciate some help.
Thank you!