AppMessage.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php
  2. namespace App\Module\Ulogic\Models;
  3. use App\Module\AppMessage\Enums\APP_MESSAGE_STATUS;
  4. use App\Module\AppMessage\Enums\APP_MESSAGE_TYPE;
  5. use App\Module\AppMessage\Enums\APP_SENDER_TYPE;
  6. use Illuminate\Database\Eloquent\Model;
  7. use Illuminate\Database\Eloquent\Relations\HasMany;
  8. /**
  9. * 应用消息模型
  10. * field start
  11. * field end
  12. *
  13. * @property-read \Illuminate\Database\Eloquent\Collection|AppMessageRecipient[] $recipients 消息接收者列表
  14. */
  15. class AppMessage extends Model
  16. {
  17. /**
  18. * 数据表名称
  19. *
  20. * @var string
  21. */
  22. protected $table = 'app_messages';
  23. // attrlist start
  24. protected $fillable = [
  25. ];
  26. // attrlist end
  27. /**
  28. * 可批量赋值的属性
  29. *
  30. * @var array
  31. */
  32. protected $fillable = [
  33. 'type', // 消息类型
  34. 'title', // 消息标题
  35. 'content', // 消息内容
  36. 'data', // 消息附加数据
  37. 'sender_id', // 发送者ID
  38. 'sender_type', // 发送者类型
  39. 'status' // 消息状态
  40. ];
  41. /**
  42. * 属性类型转换
  43. *
  44. * @var array
  45. */
  46. protected $casts = [
  47. 'data' => 'array',
  48. 'status' => APP_MESSAGE_STATUS::class,
  49. 'type' => APP_MESSAGE_TYPE::class,
  50. 'sender_type' => APP_SENDER_TYPE::class
  51. ];
  52. /**
  53. * 获取消息接收者列表
  54. *
  55. * 一条消息可以有多个接收者,这里定义了一对多关系
  56. *
  57. * @return HasMany
  58. */
  59. public function recipients(): HasMany
  60. {
  61. return $this->hasMany(AppMessageRecipient::class, 'message_id');
  62. }
  63. /**
  64. * 获取指定用户的未读消息数量
  65. *
  66. * @param int $userId 用户ID
  67. * @return int 未读消息数量
  68. */
  69. public static function getUnreadCount(int $userId): int
  70. {
  71. return static::whereHas('recipients', function ($query) use ($userId) {
  72. $query->where('user_id', $userId)
  73. ->where('is_read', false);
  74. })->count();
  75. }
  76. /**
  77. * 将消息标记为已读
  78. *
  79. * @param int $messageId 消息ID
  80. * @param int $userId 用户ID
  81. * @return bool 是否标记成功
  82. */
  83. public static function markAsRead(int $messageId, int $userId): bool
  84. {
  85. return static::whereHas('recipients', function ($query) use ($messageId, $userId) {
  86. $query->where('message_id', $messageId)
  87. ->where('user_id', $userId);
  88. })->update([
  89. 'is_read' => true,
  90. 'read_at' => now()
  91. ]);
  92. }
  93. }