[英]Get chat data and sort by receiver and sender id
我有一個問題。
我有一個這樣的數據庫:
messages_id | int | Auto-increment
from | int
to | int
message | text
現在,我在按發件人ID分組時遇到了問題。 我只想檢索已登錄用戶發送或接收的消息。這並不難。
SELECT * FROM messages WHERE from = 1 OR to = 1 ORDER BY messages_id ASC
但是現在,它們尚未分組。 由於其他人可以向此用戶發送消息。 我真的不知道從哪里開始。
我想要這樣的東西:
array(
[5] => array(
[0] => "message One",
[1] => "Message two"
),
[32] => array(
[0] => "message One",
[1] => "Message two"
)
);
5和32是一直在聊天的人的ID。
希望你們能幫助:)
感謝您的所有答復。 真的很欣賞它,但是我已經自己弄清楚了;)
現在我得到以下內容:
$currentUserID = get_current_user_id();
$rows = $wpdb->get_results("SELECT * FROM `messages` WHERE `from` = '" . $currentUserID . "' OR `to` = '" . currentUserID . "' ORDER BY `messages_id` ASC");
$messages = [];
foreach($rows as $row) {
if($row->from == $currentUserID) {
$messages[$row->to][] .= $row->message;
}
else {
$messages[$row->from][] .= $row->message;
}
}
print_r($messages);
幾年前,我遇到了這樣的問題。 我這樣做:
select 'In' as MessageDirection, `From` as Contact, `To` as UserId, Message
from Messages
where `To` = 1
union
select 'Out' as MessageDirection, `To` as Contact, `From` as UserId, Message
from Messages
where `From` = 1
order by Contact
嘗試以下操作:(假定每個字段必須具有Auto-increment_from
或to
。對於接收到的案例, to
字段具有值
SELECT *, if(`Auto-increment_from` = 1 , 'From' , 'From') as meaage_type
FROM messages WHERE from = 1 OR to = 1 ORDER BY messages_id ASC
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.