0

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

2
  • have you defined any relationship for your two tables? Commented Apr 1, 2021 at 5:12
  • yes i have defined it Commented Apr 1, 2021 at 6:30

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

1 Comment

You can use this:- whatsapp_histories::with('whm',function($join){ $join->on('whatsapp_histories.id','=','wmh.whatsapp_history_id'); $join->orderBy('wmh.created_at','ASC); }) ->select('whatsapp_histories.*','wmh.created_at') ->orderBy('whatsapp_histories.created_at','ASC') ->get();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.