<?php
|
|
namespace app\common\model\plus\business\chat;
|
|
use app\common\model\BaseModel;
|
|
/**
|
* 名片聊天会话模型
|
*/
|
class Conversation extends BaseModel
|
{
|
protected $pk = 'conversation_id';
|
protected $name = 'business_conversation';
|
|
/**
|
* 关联名片
|
*/
|
public function businessCard()
|
{
|
return $this->belongsTo("app\\common\\model\\plus\\business\\Business", 'business_card_id', 'business_card_id');
|
}
|
|
/**
|
* 关联参与者
|
*/
|
public function participants()
|
{
|
return $this->hasMany("app\\common\\model\\plus\\business\\chat\\Participant", 'conversation_id', 'conversation_id');
|
}
|
|
/**
|
* 关联消息
|
*/
|
public function messages()
|
{
|
return $this->hasMany("app\\common\\model\\plus\\business\\chat\\Chat", 'conversation_id', 'conversation_id');
|
}
|
|
/**
|
* 创建会话
|
* @param int $businessCardId 名片ID
|
* @param array $participants 参与者数组
|
* @param int $appId 应用ID
|
* @return int|false
|
*/
|
public function createConversation($businessCardId, $participants = [])
|
{
|
// 检查是否已存在相同名片的会话
|
$existing = $this->where('business_card_id', $businessCardId)->find();
|
if ($existing) {
|
return $existing->conversation_id;
|
}
|
|
$data = [
|
'business_card_id' => $businessCardId,
|
];
|
try {
|
$this->save($data);
|
$conversationId = $this->conversation_id;
|
// 添加参与者
|
foreach ($participants as $userId) {
|
(new Participant())->addParticipant($conversationId, $userId);
|
}
|
return $conversationId;
|
} catch (\Exception $e) {
|
$this->error = $e->getMessage();
|
return false;
|
}
|
}
|
|
/**
|
* 获取用户相关的会话列表
|
* @return array|\think\Paginator
|
*/
|
public function getUserConversations($param = [])
|
{
|
return $this->with(['businessCard', 'participants.user', 'messages'])
|
->order('update_time', 'desc')
|
->paginate($param);
|
}
|
|
/**
|
* 根据名片ID获取会话
|
* @param int $businessCardId 名片ID
|
* @return array|null
|
*/
|
public function getConversationByBusinessCard($businessCardId)
|
{
|
return $this->with(['businessCard', 'participants.user'])
|
->where('business_card_id', $businessCardId)
|
->find();
|
}
|
|
/**
|
* 更新会话时间
|
* @param int $conversationId 会话ID
|
* @return bool
|
*/
|
public function updateConversationTime($conversationId)
|
{
|
$conversation = $this->find($conversationId);
|
if ($conversation) {
|
$conversation->update_time = time();
|
return $conversation->save();
|
}
|
return false;
|
}
|
}
|