2

Im tried this to work it using Laravel Eloquent but i cant get exact query. So i make a raw query to get the data i want. Any one help me how to convert this into laravel eloquent or Query builder?

SELECT users.*,
       chat.*
FROM users
LEFT JOIN
  (SELECT a.customer_id,
          a.time,
          b.content
   FROM
     (SELECT customer_id,
             MAX(datetimestamp) TIME
      FROM chat_messages
      GROUP BY customer_id) a
   JOIN chat_messages b ON a.customer_id = b.customer_id
   AND a.time = b.datetimestamp) chat ON users.id = chat.customer_id
WHERE users.customer_role != 0
ORDER BY TIME DESC
M Khalid Junaid
  • 63,861
  • 10
  • 90
  • 118
AbingPj
  • 619
  • 8
  • 18

1 Answers1

2

I think you are trying to get latest chat message for each user , your query can be rewritten using left join to pick the latest record per group and it would be easier to transform such query in laravel's query builder format

SQL

select u.*,c.*
from users u
join chat_messages c on u.id = c.customer_id
left join chat_messages c1 on c.customer_id = c1.customer_id and c.datetimestamp < c1.datetimestamp
where c1.customer_id is null
    and u.customer_role != 0
order by c.datetimestamp desc

Query Builder

DB::table('users as u')
  ->select('u.*, c.*')
  ->join('chat_messages as c', 'u.id', '=', 'c.customer_id' )
  ->leftJoin('chat_messages as c1', function ($join) {
        $join->on('c.customer_id', '=', 'c1.customer_id')
             ->whereRaw(DB::raw('c.datetimestamp < c1.datetimestamp'));
   })
  ->whereNull('c1.customer_id')
  ->where('u.customer_role','!=',0)
  ->orderBy('c.datetimestamp', 'desc')
  ->get();

Reference:Laravel Eloquent select all rows with max created_at

M Khalid Junaid
  • 63,861
  • 10
  • 90
  • 118
  • Thanks, Yes, you are right mr. @Khalid,. I`m getting the latest chat message for each user,. It is posible using models? ,.. your answer have different results. – AbingPj Aug 13 '20 at 02:02
  • @AbingPj it is possible using models but you won't be able to sort users based on latest chat like using `with()` method, for results don't match can you add a sample data then we can compare results of both query versions – M Khalid Junaid Aug 13 '20 at 05:29