简体   繁体   中英

SQL Query to Laravel Eloquent

I have this query below and i want to convert it to Laravel Eloquent. I have tried with no success.

select A.client_id, max(A.purchase_date)
from gym_client_purchases A
left Join gym_clients B on B.id = A.client_id
group by A.client_id
order By max(A.purchase_date) desc

I tried this but i get the oldest record from each user.

$this->data['expiringSubscriptions'] = Gym::select('first_name', 'last_name', 'gym_client_purchases.*')
->leftJoin('gym_clients', 'gym_clients.id', '=', 'client_id')
->groupBy('client_id')
->orderBy('gym_client_purchases.purchase_date', 'desc')
->get(); 

Could anyone guide me to convert my queries?

Thank you.

You didn't mention any models, so here it is using the query builder.

$results = DB::table('gym_client_purchases gcp')
    ->selectRaw('gcp.client_id, MAX(gcp.purchase_date) AS max_purchase_date')
    ->leftJoin('gym_clients gc', 'gc.id', '=', 'gcp.client_id')
    ->groupBy('gcp.client_id')
    ->orderBy('max_purchase_date', 'desc');

Haven't run it - but that should be basically it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM