0

目前,我在将对象推送到我的 mongodb“消息”集合中的现有数组时遇到问题。

该集合用于存储两个用户之间的消息,具有“user_id”、“recipient”和“messages”三个字段。Messages 字段是一个数组,其中将包含一个消息对象数组。

创建时,触发以下函数,文档按预期出现在 mongodb 中,三个字段正确显示。更重要的是,出现了“messages”数组字段,其中包含初始对象。

    public function sendDirectMessage(Request $request)
    {
        $user = User::find($request->user()->id);
        $data = $request->only(['message', 'recipient']);
        broadcast(new DirectMessageEvent($data, $user))->toOthers(); //only broadcast new message sent event to recipient user
        //Check conversation between two users exists
        $chat = Message::where('user_id', '=', $user->id)->where('recipient', '=', $request->recipient)->get();
        //if doesnt exist, create new document
        if($chat->count() == 0){
            Message::create([
                'user_id' => $user->id,
                'recipient' => $request->recipient,
                'messages' => array([
                    "from" => $user->first_name,
                    "message" => $request->message
                    ]) //messages stored as subcollection
            ]);
        }

但是,当两个用户之间的现有对话已经存在,并且我尝试将接收到的消息对象推送到消息数组时,代码会正常执行,但对象不会出现在消息数组中。

        else {
            //push message to messages array
            $chat->push('messages', ([
                'from' => 'Jane Doe',
                'message' => 'Hi John',
            ]));
            dd($chat);
        
        }
        return response()->json([
            "Message" => "Successfully sent a private message to user ".$request->recipient
        ], 200);
    }

对此的任何帮助将不胜感激。

4

1 回答 1

0

问题似乎与查询结果的存储方式和聊天变量的访问方式有关。一旦我更改了下面的代码,问题就不再发生了。

        $chat = Message::where('user_id', '=', $user->id)->where('recipient', '=', $request->recipient);
        //if doesnt exist, create new document
        if($chat->get()->count() == 0){
            Message::create([
                'user_id' => $user->id,
                'recipient' => $request->recipient,
                'messages' => array([
                    "from" => $user->first_name,
                    "message" => $request->message
                    ]) //messages stored as subcollection
            ]);
        }
        else {
            //push message to messages array
            $chat->push('messages', [
                "message" => "hello"
            ]);
        
            dd($chat->get());
于 2022-02-18T10:37:37.070 回答