AppMessage.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. /**
  24. * 可批量赋值的属性
  25. *
  26. * @var array
  27. */
  28. protected $fillable = [
  29. 'type', // 消息类型
  30. 'title', // 消息标题
  31. 'content', // 消息内容
  32. 'data', // 消息附加数据
  33. 'sender_id', // 发送者ID
  34. 'sender_type', // 发送者类型
  35. 'status' // 消息状态
  36. ];
  37. /**
  38. * 属性类型转换
  39. *
  40. * @var array
  41. */
  42. protected $casts = [
  43. 'data' => 'array',
  44. 'status' => APP_MESSAGE_STATUS::class,
  45. 'type' => APP_MESSAGE_TYPE::class,
  46. 'sender_type' => APP_SENDER_TYPE::class
  47. ];
  48. /**
  49. * 获取消息接收者列表
  50. *
  51. * 一条消息可以有多个接收者,这里定义了一对多关系
  52. *
  53. * @return HasMany
  54. */
  55. public function recipients(): HasMany
  56. {
  57. return $this->hasMany(AppMessageRecipient::class, 'message_id');
  58. }
  59. /**
  60. * 获取指定用户的未读消息数量
  61. *
  62. * @param int $userId 用户ID
  63. * @return int 未读消息数量
  64. */
  65. public static function getUnreadCount(int $userId): int
  66. {
  67. return static::whereHas('recipients', function ($query) use ($userId) {
  68. $query->where('user_id', $userId)
  69. ->where('is_read', false);
  70. })->count();
  71. }
  72. /**
  73. * 将消息标记为已读
  74. *
  75. * @param int $messageId 消息ID
  76. * @param int $userId 用户ID
  77. * @return bool 是否标记成功
  78. */
  79. public static function markAsRead(int $messageId, int $userId): bool
  80. {
  81. return static::whereHas('recipients', function ($query) use ($messageId, $userId) {
  82. $query->where('message_id', $messageId)
  83. ->where('user_id', $userId);
  84. })->update([
  85. 'is_read' => true,
  86. 'read_at' => now()
  87. ]);
  88. }
  89. }