| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- <?php
- namespace App\Module\Ulogic\Models;
- use App\Module\AppMessage\Enums\APP_MESSAGE_STATUS;
- use App\Module\AppMessage\Enums\APP_MESSAGE_TYPE;
- use App\Module\AppMessage\Enums\APP_SENDER_TYPE;
- use Illuminate\Database\Eloquent\Model;
- use Illuminate\Database\Eloquent\Relations\HasMany;
- /**
- * 应用消息模型
- * field start
- * field end
- *
- * @property-read \Illuminate\Database\Eloquent\Collection|AppMessageRecipient[] $recipients 消息接收者列表
- */
- class AppMessage extends Model
- {
- /**
- * 数据表名称
- *
- * @var string
- */
- protected $table = 'app_messages';
- // attrlist start
- protected $fillable = [
- ];
- // attrlist end
- /**
- * 可批量赋值的属性
- *
- * @var array
- */
- protected $fillable = [
- 'type', // 消息类型
- 'title', // 消息标题
- 'content', // 消息内容
- 'data', // 消息附加数据
- 'sender_id', // 发送者ID
- 'sender_type', // 发送者类型
- 'status' // 消息状态
- ];
- /**
- * 属性类型转换
- *
- * @var array
- */
- protected $casts = [
- 'data' => 'array',
- 'status' => APP_MESSAGE_STATUS::class,
- 'type' => APP_MESSAGE_TYPE::class,
- 'sender_type' => APP_SENDER_TYPE::class
- ];
- /**
- * 获取消息接收者列表
- *
- * 一条消息可以有多个接收者,这里定义了一对多关系
- *
- * @return HasMany
- */
- public function recipients(): HasMany
- {
- return $this->hasMany(AppMessageRecipient::class, 'message_id');
- }
- /**
- * 获取指定用户的未读消息数量
- *
- * @param int $userId 用户ID
- * @return int 未读消息数量
- */
- public static function getUnreadCount(int $userId): int
- {
- return static::whereHas('recipients', function ($query) use ($userId) {
- $query->where('user_id', $userId)
- ->where('is_read', false);
- })->count();
- }
- /**
- * 将消息标记为已读
- *
- * @param int $messageId 消息ID
- * @param int $userId 用户ID
- * @return bool 是否标记成功
- */
- public static function markAsRead(int $messageId, int $userId): bool
- {
- return static::whereHas('recipients', function ($query) use ($messageId, $userId) {
- $query->where('message_id', $messageId)
- ->where('user_id', $userId);
- })->update([
- 'is_read' => true,
- 'read_at' => now()
- ]);
- }
- }
|