简体   繁体   中英

Laravel 6, MYSQL - How to Left Join a Sub Query with GroupBY using Laravel Querybuilder or Model Eloquent?

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

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

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