我现在更新了整个问题。

我有用于存储用户消息的消息表。通过使用此表,我可以列出给用户的消息,但也尝试像Facebook一样在消息的左侧列出对话。

我想出了必要的查询:

"SELECT correspondent, MAX(updated_at) as date FROM (SELECT sender_id as correspondent,updated_at FROM messages WHERE recipient_id = #{current_user.id} UNION ALL SELECT recipient_id as correspondent, updated_at FROM messages WHERE sender_id = #{current_user.id}) x GROUP BY correspondent ORDER BY date desc"


问题是我使用find_by_sql()函数检索数据。现在的问题是,如何根据Active Record编写此查询?

最佳答案

既然已经有了SQL查询,为什么不仅仅执行该查询以获得预期的结果呢?

sql_query = "SELECT correspondent, MAX(updated_at) as date FROM (SELECT sender_id as correspondent,updated_at FROM messages WHERE recipient_id = #{current_user.id} UNION ALL SELECT recipient_id as correspondent, updated_at FROM messages WHERE sender_id = #{current_user.id}) x GROUP BY correspondent ORDER BY date desc"
results = ActiveRecord::Base.connection.execute(sql_query)
# use results e.g. loop through them in your program


然后,您可以根据需要在Rails应用程序中使用results

关于mysql - 如何在消息传递系统中列出对话,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33181634/

10-11 01:27