Laravel Eloquent 'WITH' statement query

How to convert this mysql query to Eloquent

with wmh as (select * from whatsapp_message_histories ORDER BY created_at LIMIT 1) 

select DISTINCT whatsapp_histories.*, wmh.created_at from whatsapp_histories

left join wmh on wmh.whatsapp_history_id = whatsapp_histories.id

ORDER BY wmh.created_at

Please Help me, thanks a lot!

(Edited) My Problem is, I have Eloquent Model whatsapp_histories, has a relation to whatsapp_message_histories (using hasMany). My Objective is need to display whatsapp_histories order by whatsapp_message_histories.created_at. (This is eloquent, because i need to display other whatsapp_histories's relation). I can solve it in native way, but not in eloquent, but i'm not allowed to change the previous eloquent code

Upvotes: 0

Views: 207

Answers (1)

Varinder Kaur
Varinder Kaur

Reputation: 84

Try this:-

whm::with('whatsapp_histories',function($join){
   $join->on('wmh.whatsapp_history_id','=','whatsapp_histories.id');
   $join->orderBy('whatsapp_histories.created_at','ASC');
   $join->limit(1);
})->orderBy('wmh.created_at','ASC)->get();

Upvotes: 1

Related Questions