获取最新消息postgres

时间:2018-12-04 17:42:17

标签: sql laravel postgresql

我正在使用Laravel建立类似聊天的内容,我想从用户X和Y获取最后一条消息:

我有这张叫做“邮件”的表

id integer
receiver_id integer references user
sender_id integer references user
message text
created_at datetime

我在这里收到一条消息,何时何人发送该消息;

       $user = JWTAuth::toUser();
       $messages = DB::table("messages")
            ->select(DB::raw(
                "least(sender_id, receiver_id) as user_1,
               greatest(sender_id, receiver_id) as user_2,
               max(created_at) as last_timestamp,
               max(message) as message"))
            ->where("sender_id", $user->id)
            ->orWhere("receiver_id", $user->id)
            ->groupBy(DB::raw("least(sender_id, receiver_id), greatest(sender_id, receiver_id)"))
            ->orderBy("last_timestamp", "desc")
            ->get();

    $message_info = array();

    foreach($messages as $k => $m) {
        $message_info[$k]['message'] = $m->message;
        $message_info[$k]['last_message'] = $m->last_timestamp;
        if($m->user_2 == $user->id){
            $message_info[$k]['user_id'] = $m->user_1;
        }else{
            $message_info[$k]['user_id'] = $m->user_2;
        }
    }

在这里列出有消息的用户

    $listUserHaveMessage = [];

    foreach ($messages as $message){
        if($message->user_2 == $user->id){
            $listUserHaveMessage[] = $message->user_1;
        }else{
            $listUserHaveMessage[] = $message->user_2;
        }
    }

这里是没有发送邮件的用户

    $notMessage = User::where("client_id",'=',$user->client_id)
        ->where("id","!=", $user->id)
        ->where("is_visible",'=', true)
        ->whereNotIn("id", $listUserHaveMessage)
        ->get();
    foreach ($notMessage as $m){
        $listUserNotHaveMessage[] = $m->id;
    }

现在,我将数组与查询合并以获取所有用户

    $list_users = array_merge($listUserHaveMessage, $listUserNotHaveMessage);
    $idsImploded = implode(',',$list_users);
    $users = User::where("client_id",'=',$user->client_id)
        ->where("id","!=", $user->id)
        ->where("is_visible",'=', true)
        ->whereIn("id", $list_users)
        ->orderByRaw(DB::raw("position(id::text in '$idsImploded')"))
        ->get();

    $outPut = array();

    foreach($users as $k => $u){
        $outPut['usuarios'][$k] = $u;
    }

我的问题是: 如何将最后一条消息合并到用户数组? 有办法吗?

谢谢

0 个答案:

没有答案