I need help converting the following raw query into a Laravel query using the DB query builder. The query must be built using the DB (facade) query builder and not Eloquent.
SELECT distinct p.client_id
FROM people p
JOIN (SELECT client_id, COUNT(*)
FROM people
GROUP BY client_id
HAVING count(client_id) > 1 ) b
ON p.client_id = b.client_id
ORDER BY p.client_id')
This is my solution so far:
$subQuery = DB::table('people')
->select('client_id', DB::raw('count(*)'))
->groupBy('client_id')
->havingRaw('count(client_id) > ?', [1]);
$mainQuery = DB::table('people')
->distinct('client_id')
->joinSub($subQuery, 'b', function ($join) {
$join->on('people.client_id', '=', 'b.client_id');
})
->orderBy('client_id')
->get();