Message.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\controller\Api;
  4. use think\Db;
  5. /**
  6. * 系统消息
  7. */
  8. class Message extends Api
  9. {
  10. protected $noNeedLogin = [];
  11. protected $noNeedRight = ['*'];
  12. //查询未读系统消息数量
  13. public function unreadnum() {
  14. $num = Db::name('message')->where(['user_id'=>$this->auth->id,'status'=>0])->count('id');
  15. $content = Db::name('message')->where(['user_id'=>$this->auth->id])->order('id desc')->value('content');
  16. $data['num'] = $num;
  17. $data['content'] = $content ? : '';
  18. //系统消息未读数量
  19. $sys_ids = Db::name('message_sys')->column('id');
  20. $all_num = count($sys_ids);
  21. $read_num = Db::name('user_messagesys')->where('user_id',$this->auth->id)->where('msg_id','IN',$sys_ids)->count();
  22. $data['msgsys_unread_num'] = $all_num > $read_num ? $all_num - $read_num : 0; //因公告被删除,未读公告没来得及删除,相减可能会负数
  23. $this->success('success', $data);
  24. }
  25. //我的消息列表
  26. public function mylist(){
  27. $list = Db::name('message')->where('user_id',$this->auth->id)->autopage()->order('id desc')->select();
  28. //读取即为已读
  29. $map = [
  30. 'user_id' => $this->auth->id,
  31. 'status' => 0,
  32. ];
  33. Db::name('message')->where($map)->update(['status'=>1]);
  34. $this->success('success',$list);
  35. }
  36. /*
  37. * 获取系统消息列表
  38. */
  39. public function getmessagesys() {
  40. $list = Db::name('message_sys')->autopage()->order('id desc')->select();
  41. Db::startTrans();
  42. //系统消息
  43. //全部未读
  44. $rs = Db::name('user_messagesys')->where('user_id',$this->auth->id)->delete();
  45. if($rs === false){
  46. Db::rollback();
  47. $this->error('操作失败');
  48. }
  49. //循环全部已读
  50. $list2 = Db::name('message_sys')->column('id');
  51. if(!empty($list2)){
  52. $newall = [];
  53. foreach($list2 as $key => $msg_id){
  54. $newall[] = [
  55. 'user_id' => $this->auth->id,
  56. 'msg_id' => $msg_id,
  57. ];
  58. }
  59. if(!empty($newall)){
  60. $rs = Db::name('user_messagesys')->insertAll($newall);
  61. if($rs === false){
  62. Db::rollback();
  63. $this->error('操作失败');
  64. }
  65. }
  66. }
  67. Db::commit();
  68. $this->success("获取成功!",$list);
  69. }
  70. }