Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel join with limit

I have the following working for laravel paginate

$query = DB::table('clients')
            ->leftJoin('radusergroup', 'clients.username', '=', 'radusergroup.username')
            ->leftJoin('recharge', 'clients.username', '=', 'recharge.soldto');

I want to join some values from two tables radusergroup and recharge. radusergroup always return one row as it has only one row stored whereas recharge table return multiple rows. I want only one row returned from recharge table which is latest entry.

Right now its return all the possible rows from recharge table and showing it on paginated view.

like image 873
Dineshh Bhardwaj Avatar asked Oct 26 '25 14:10

Dineshh Bhardwaj


1 Answers

This is Laravel Official documentation

DB::table('clinets')
     ->leftJoin('radusergroup', 'clients.username', '=', 'radusergroup.username')
    ->leftJoin('recharge', function ($leftJoin) {
        $leftJoin->on('clients.username', '=', 'recharge.soldto')
             ->where('recharge.create_date', '=', DB::raw("(select max(`create_date`) from recharge)"));
    })
    ->get();

this is the case if you have create_date column in your table, if you haven't got it I strongly recommend to create that column.

like image 120
Vahe Galstyan Avatar answered Oct 29 '25 16:10

Vahe Galstyan