Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

beyond's avatar

I need equivalent eloquent query

I want to run this query with eloquent.

SELECT * FROM users WHERE id IN (SELECT worker_id from projects up WHERE (SELECT COUNT(*) from projects below WHERE status = 2 and below.worker_id= up.worker_id) > 2 GROUP BY below.worker_id)

Below is the attempt which fails and the issues is how to use the count within the subquery as it up in the pure mysql query.

User::whereIn('id', function($query){ $query->select('worker_id') ->from('projects as up') ->where(function($query){ $query->selectRaw('COUNT(*) as count') ->from('projects as below') ->where('status', 2) ->having('count', '>', 2) ->having('below.worker_id', '=', 'up.worker_id') ->groupBy('below.worker_id') }) ; })->get();

0 likes
7 replies
beyond's avatar

The steps below solves it but I want it to be just one process:

$ids= DB::table('projects')->selectRaw('COUNT(*) as count, worker_id') ->where('status', 2) ->having('count', '>', 2) ->groupBy('worker_id') ->pluck('worker_id');

        $users= User::whereIn('id', $ids)
        ->get();
Tray2's avatar

You can use whereIn

$users = DB::table('users')
                    ->whereIn('id', [1, 2, 3])
                    ->get();

and havingRaw

$orders = DB::table('orders')
                ->select('department', DB::raw('SUM(price) as total_sales'))
                ->groupBy('department')
                ->havingRaw('SUM(price) > ?', [2500])
                ->get();

and subqueries

$users = User::where(function ($query) {
    $query->select('type')
        ->from('membership')
        ->whereColumn('user_id', 'users.id')
        ->orderByDesc('start_date')
        ->limit(1);
}, 'Pro')->get();

All the code examples are from the docs.

https://laravel.com/docs/7.x/queries

edoc's avatar

whereIn takes an anonymous function as a subquery

you should be able to do something like this:

$users= User::whereIn('id', function ($q) {
	$q->select('worker_id')->from('projects')->where('status', 2) ->havingRaw('COUNT(*) > 2') ->groupBy('worker_id');

})->get();

Not tested

beyond's avatar

I'm sorry, I had no reply. And u thought about chances of getting answers from laravel category due to the traffic here.

jlrdw's avatar

But I gave the exact same reply on that other post. But rather than copying and pasting the examples I referred you to the query Builder chapter which has all of those examples. So I'm confused on why you said you didn't get no reply.

@TaylorOtwell included many great examples to learn from all through the documentation.

But no worries, everything is okay.

Please or to participate in this conversation.