Diego Vieira
Diego Vieira

Reputation: 199

Convert SQL into Laravel Eloquent

I have this SQL query:

SELECT
  m1.id
FROM
  messages m1
WHERE
  m1.to_id = 1 AND m1.created_at < (
    SELECT 
      m2.created_at
    FROM
      messages m2
    WHERE
      m2.from_id = m1.to_id AND m2.to_id = m1.from_id)
GROUP BY
    m1.id

How can i convert into eloquent? I done this until now, but a don't know what to do in the part of where on subquery.

Message::where('to_id', 1)
            ->where('created_at', '<', function($q) {
               $q->from('messages');
               $q->select('created_at');
            })
            ->select('id')
            ->groupBy('id')
            ->get();

Upvotes: 0

Views: 41

Answers (1)

Nazmul Hasan
Nazmul Hasan

Reputation: 1977

You can try this:

Message::where('to_id', 1)
            ->where('created_at', '<', function($q) {
                $q->from('messages AS m2')
                  ->select('created_at')
                  ->where('m2.from_id ','=', 'messages.to_id ')
                  ->where('m2.to_id','=','messages.from_id');
            })
            ->select('id')
            ->groupBy('id')
            ->get();

Upvotes: 1

Related Questions