我正在使用 ColdFusion 创建一个新的聊天系统,但我在解决一个小问题时遇到了很多麻烦。
首先,我将解释系统是如何工作的。与某人创建新聊天时,它会在 MySQL 表中创建一个对话行conversations
。之后,用户可以互相发送消息。发送消息时,会在表中插入一行,conversations_messages
其中包含时间戳、发送消息的用户、消息,当然还有消息的 id。听起来合乎逻辑,但现在出现了大问题:组织所有这些消息。
用户可以在一个页面上查看他们与其他人的消息,这是该页面的代码:
// Check conversation ID based on page url
<cfif IsDefined('URL.chat') and URL.chat neq "">
// Load conversation based on page url
<cfquery name = "getconv" datasource = "#DSN#">
SELECT *
FROM `conversations`
</cfquery>
// Get all messages from this conversation
<cfoutput query="getconv">
<cfquery name = "getmessages" datasource = "#DSN#">
SELECT *
FROM `conversations_messages`
WHERE `conversation` = '#chat#'
ORDER BY `conversations_messages`.`id` DESC
</cfquery>
// Get messages sent by 'user_one'
<cfquery name = "my" datasource = "#DSN#">
SELECT *
FROM `conversations_messages`
WHERE `conversation` LIKE '#chat#'
AND `user` LIKE '#user.id#'
ORDER BY `conversations_messages`.`id` DESC
</cfquery>
// Get messages sent by 'user_two'
<cfquery name = "friend" datasource = "#DSN#">
SELECT *
FROM `conversations_messages`
WHERE `conversation` LIKE '#chat#'
AND `user` LIKE '#getconv.user_two#'
</cfquery>
<div class="content">
// Messages sent by 'user_one' aka. user that created conversation
You: <cfoutput><cfloop query="my">#my.message#<br></cfloop></cfoutput>
// Messages sent by 'user_two'
Friend: <cfoutput><cfloop query="friend">#friend.message#</cfloop></cfoutput>
</cfoutput>
</div>
</cfif>
这就是结果现在的显示方式:(如您所见,它是按用户排序的)
我希望它按消息 ID 排序,所以它显示如下:
我希望现在更清楚一点!帮助将不胜感激!