MsgController.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. namespace App\Http\Controllers\V1;
  3. use App\Models\Msg;
  4. use App\Models\MsgRead;
  5. use App\Models\Product;
  6. use Illuminate\Http\Request;
  7. class MsgController extends Controller
  8. {
  9. public function __construct()
  10. {
  11. $this->user = auth('api')->user();
  12. $this->userId = $this->user ? $this->user->id : 0;
  13. //如果用户被删除,会自动退出登录
  14. if (!empty($this->user->deleted_at)) {
  15. $this->user->online = 0;
  16. $this->user->save();
  17. auth('api')->logout();
  18. }
  19. }
  20. /**
  21. * @return void
  22. * 消息列表
  23. */
  24. public function msgList(Request $request){
  25. $limit = $request->get('limit',10);
  26. $list = Msg::query()->with('user:id,name,avatar')->withCount(['read' => function($item){
  27. $item->where('user_id',$this->userId);
  28. }])->where('to_user_id',$this->userId)
  29. ->orWhere('to_user_id',0)
  30. ->orderByDesc("id")
  31. ->paginate($limit);
  32. foreach ($list as $v){
  33. if($v){
  34. $v['productList'] = Product::select('id','image')->whereIn('id',explode(',',$v['product_id']))->get();
  35. $v['is_read'] = $v['read_count'];
  36. }
  37. }
  38. return $this->success($this->page($list));
  39. }
  40. /**
  41. * @param Request $request
  42. * @return void
  43. * 消息详情
  44. */
  45. public function msgDetail(Request $request){
  46. $id = $request->get('id');
  47. if(!$id){
  48. return $this->error("缺少参数ID!");
  49. }
  50. $msg = Msg::query()->with('user:id,name,avatar')->where('id',$id)->first();
  51. $MsgRead = MsgRead::query()->where('user_id',$this->userId)->where('msg_id',$msg['id'])->count();
  52. if(!$MsgRead){
  53. $data =[
  54. 'user_id'=>$this->userId,
  55. 'msg_id'=>$msg['id']
  56. ];
  57. MsgRead::query()->create($data); // 已读
  58. }
  59. return $this->success($msg);
  60. }
  61. public function getNewMsgState(){
  62. $read = Msg::join('msg_read','msg.id','=','msg_read.msg_id')->count();
  63. $msg = Msg::where('to_user_id',$this->userId)->count();
  64. return $this->success([
  65. 'isNewMsg' => ($msg - $read) > 0 ? 1 : 0
  66. ]);
  67. }
  68. }