我试图使用Laravel eloquent在MySQL中获取最后一条消息。我有桌子
我尝试了下面的代码,但它没有返回最后一条消息。
return $this->chat->join("chats_users", "chats_users.chat_id", "=", "chats.id")
->join("chats_reply", "chats_reply.chat_id", "=", "chats.id")
->where("chats_users.user_id", "=", $user_id)
->take($limit)
->skip($offset)
->groupBy("chats_reply.chat_id")
->get();
我也尝试过:
return \DB::select( \DB::raw("SELECT * FROM chats_reply msg inner join ( select max(created_at) created_at, message from chats_reply group by chat_id) m2 on msg.created_at = m2.created_at INNER JOIN chats_users mst ON mst.chat_id=msg.chat_id WHERE mst.user_id=$user_id") );
答案 0 :(得分:1)
这确实奏效了。
\DB::select( \DB::raw(
"SELECT * FROM chats_reply msg
INNER JOIN (
SELECT max(created_at) created_at FROM chats_reply GROUP BY chat_id ORDER BY created_at
) m2
ON msg.created_at = m2.created_at
"
)
);