<?php
|
|
namespace app\common\model\plus\business\chat;
|
|
use app\common\model\BaseModel;
|
|
/**
|
* 名片聊天消息模型
|
*/
|
class Chat extends BaseModel
|
{
|
protected $pk = 'chat_id';
|
protected $name = 'business_chat';
|
|
// 消息类型常量
|
const MESSAGE_TYPE_TEXT = 0; // 文本消息
|
const MESSAGE_TYPE_IMAGE = 1; // 图片消息
|
|
// 消息状态常量
|
const MESSAGE_STATUS_SENT = 0; // 已发送
|
const MESSAGE_STATUS_READ = 1; // 已读
|
|
/**
|
* 关联发送者
|
*/
|
public function sender()
|
{
|
return $this->belongsTo("app\\common\\model\\user\\User", 'sender_id', 'user_id');
|
}
|
|
/**
|
* 关联会话
|
*/
|
public function conversation()
|
{
|
return $this->belongsTo("app\\common\\model\\plus\\business\\chat\\Conversation", 'conversation_id', 'conversation_id');
|
}
|
|
/**
|
* 发送消息
|
* @param int $conversationId 会话ID
|
* @param int $senderId 发送者ID
|
* @param string $content 消息内容
|
* @param int $messageType 消息类型
|
* @param int $appId 应用ID
|
* @return bool
|
*/
|
public function sendMessage($conversationId, $senderId, $content, $messageType = 0, $appId = null)
|
{
|
$data = [
|
'conversation_id' => $conversationId,
|
'sender_id' => $senderId,
|
'content' => $content,
|
'message_type' => $messageType,
|
'is_read' => 0,
|
'read_time' => 0,
|
'app_id' => $appId?$appId:self::$app_id,
|
'create_time' => time(),
|
];
|
|
return $this->save($data);
|
}
|
|
/**
|
* 标记消息为已读
|
* @param int $chatId 消息ID
|
* @param int $readerId 阅读者ID
|
* @return bool
|
*/
|
public function markAsRead($chatId, $readerId)
|
{
|
$message = $this->where('chat_id',$chatId)->find();
|
if ($message && $message->sender_id != $readerId) {
|
$data=[
|
'is_read'=>1,
|
'read_time'=>time()
|
];
|
return $message->save($data);
|
}
|
return false;
|
}
|
|
/**
|
* 获取会话消息列表
|
* @return array|\think\Paginator
|
*/
|
public function getMessages($param)
|
{
|
return $this->with(['sender'])
|
->where('conversation_id', $param['conversation_id'])
|
->order('chat_id', 'desc')
|
->paginate($param);
|
}
|
|
/**
|
* 获取未读消息数量
|
* @param int $conversationId 会话ID
|
* @param int $userId 用户ID
|
* @return int
|
*/
|
public function getUnreadCount($conversationId, $userId)
|
{
|
return $this->where('conversation_id', $conversationId)
|
->where('sender_id', '<>', $userId)
|
->where('is_read', 0)
|
->count();
|
}
|
}
|