Socket/app/models/chat/ChatMessage.php

70 lines
1.7 KiB
PHP

<?php
namespace app\models\chat;
use think\Model;
/**
* 聊天消息模型
* Class ChatMessage
* @package app\models\chat
*/
class ChatMessage extends Model
{
protected $table = 'cg_chat_message';
protected $pk = 'id';
protected $autoWriteTimestamp = false;
// 发送者类型
const SENDER_USER = 1; // 用户
const SENDER_ADMIN = 2; // 客服
// 消息类型
const MSG_TYPE_TEXT = 1; // 文字
const MSG_TYPE_IMAGE = 2; // 图片
// 消息状态
const STATUS_PENDING = 0; // 待发送
const STATUS_SENT = 1; // 已发送
const STATUS_DELIVERED = 2; // 已送达
const STATUS_READ = 3; // 已读
const STATUS_FAILED = 4; // 发送失败
/**
* 获取会话消息列表
*/
public static function getBySessionId($sessionId, $limit = 50, $lastId = 0)
{
$query = self::where('session_id', $sessionId);
if ($lastId > 0) {
$query->where('id', '<', $lastId);
}
return $query->order('id', 'desc')
->limit($limit)
->select()
->toArray();
}
/**
* 获取会话未读消息
*/
public static function getUnreadBySessionId($sessionId, $senderType, $limit = 50)
{
return self::where('session_id', $sessionId)
->where('sender_type', '<>', $senderType)
->where('status', '<', self::STATUS_READ)
->order('id', 'asc')
->limit($limit)
->select()
->toArray();
}
/**
* 检查消息ID是否存在(幂等性)
*/
public static function existsByMsgId($msgId)
{
return self::where('msg_id', $msgId)->count() > 0;
}
}