如何在有效的Messenger系统查询JSON输出中识别经过身份验证的用户?

时间:2018-10-11 21:45:21

标签: laravel eloquent

我已经在两个用户之间建立了一个Messenger系统,我需要能够以雄辩的JSON输出识别经过身份验证的用户。

会话控制器

public function show(Conversation $conversation)
 {
   $conversation->load('participants');
   $messages = $conversation->messages()->with('sender')->latest()->take(5)->get()->sortBy('created_at');

   return $messages->toArray();
}

会话模型

public function participants(){
   return $this->belongsToMany('App\User' ,'conversation_participants','conversation_id','user_id');
}

JSON输出

{  
   "1":{  
      "id":59,
      "body":"Hi, what's up",
      "conversation_id":11,
      "sender_id":1,
      "type":"user_message",
      "created_at":"2018-10-01 23:43:07",
      "updated_at":"2018-10-01 23:43:07",
      "sender":{  
         "id":1,
         "username":"Jim",
         "slug":"Jim",
         "name":"Jim",
      }
   },
   "0":{  
      "id":60,
      "body":"Hi there",
      "conversation_id":11,
      "sender_id":1,
      "type":"user_message",
      "created_at":"2018-10-01 23:43:20",
      "updated_at":"2018-10-01 23:43:20",
      "sender":{  
         "id":1,
         "username":"Reggie",
         "slug":"reggie",
         "name":"Reggie",
      }
   }
}

因此,假设我以“ Jim”身份登录,我希望在JSON输出中使用一些标识符,例如"logged_in":"1"属性作为标识符,以显示Jim是已登录的用户,而"logged_in":"0"显示Reggie不是登录用户:

{  
   "1":{  
      "id":59,
      "body":"Hi, what's up",
      "conversation_id":11,
      "sender_id":1,
      "type":"user_message",
      "created_at":"2018-10-01 23:43:07",
      "updated_at":"2018-10-01 23:43:07",
      "sender":{  
         "id":1,
         "username":"Jim",
         "slug":"Jim",
         "name":"Jim",
         "logged_in":"1"
      }
   },
   "0":{  
      "id":60,
      "body":"Hi there",
      "conversation_id":11,
      "sender_id":1,
      "type":"user_message",
      "created_at":"2018-10-01 23:43:20",
      "updated_at":"2018-10-01 23:43:20",
      "sender":{  
         "id":1,
         "username":"Reggie",
         "slug":"reggie",
         "name":"Reggie",
         "logged_in":"0"
      }
   }
}

我将如何实现这一目标?

注意标识符不需要,也不必位于“发送者”对象中。

1 个答案:

答案 0 :(得分:2)

您应该可以SELECT另一列,如下所示:

$messages = $conversation
    ->messages()
    ->selectRaw('messages.*, IF(messages.sender_id = ?, 1, 0) AS logged_in', [Auth::id()])
    ->with('sender')
    ->latest()
    ->take(5)
    ->get()
    ->sortBy('created_at');

注意,我假设您正在使用MySQL。