How to join sub-query in laravel eloquent?

Member

by darion , in category: PHP Frameworks , 6 months ago

How to join sub-query in laravel eloquent?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dana , 6 months ago

@darion 

In Laravel, you can join sub-queries using the joinSub method in the Eloquent query builder. Here's an example of how to join a sub-query in Laravel Eloquent:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
use AppModelsUser;
use IlluminateSupportFacadesDB;

$subQuery = DB::table('posts')->select('user_id', DB::raw('count(*) as post_count'))->groupBy('user_id');

$users = User::select('users.*')
    ->joinSub($subQuery, 'post_count', function ($join) {
        $join->on('users.id', '=', 'post_count.user_id');
    })
    ->get();


In this example, we are first creating a sub-query that selects the count of posts by user id from the posts table. Then, we are using the joinSub method to join this sub-query with the users table based on the user id. Finally, we are retrieving the results using the get method.


You can customize the sub-query and join conditions according to your requirements.