如果您想为多个发送者、接收者和主题设置聊天,我相信这种关系很好。
另外,我无法理解您所说的 Chat 实体的确切含义,但下面的方法应该可以消除您对此方法可能存在的任何疑问。
以下是完成工作的方法!
设置关系
按以下方式设置关系
class Chat
{
public function sender()
{
return $this->morphTo();
}
public function topic()
{
return $this->morphTo();
}
public function receiver()
{
return $this->morphTo();
}
}
class SystemUser
{
public function sentChats()
{
return $this->morphMany('App\Chat', 'sender');
}
public function receivedChats()
{
return $this->morphMany('App\Chat', 'receiver');
}
}
class Customer
{
public function sentChats()
{
return $this->morphMany('App\Chat', 'sender');
}
public function receivedChats()
{
return $this->morphMany('App\Chat', 'receiver');
}
}
class Illustrate
{
public function illustrable()
{
return $this->morphTo();
}
public function chats()
{
return $this->morphMany('App\Chat', 'topic');
}
}
创建聊天
如何创建聊天
public function create()
{
$inputs = request()->only([
'sender_id', 'sender_type', 'receiver_id', 'receiver_type', 'topic_id', 'topic_type',
'message', 'in_reply_of',
]);
$sender = $this->getSender($inputs);
$receiver = $this->getReceiver($inputs);
$topic = $this->getTopic($inputs);
if($sender && $receiver && $topic) {
$chat = $sender->sentChats()->create([
'receiver_id' => $receiver->id,
'receiver_type' => get_class($receiver),
'topic_id' => $topic->id,
'topic_type' => get_class($topic),
'message' => $inputs['message'],
'in_reply_of' => $inputs['in_reply_of'],
]);
}
}
private function getSender($inputs)
{
if(isset($inputs['sender_type'], $inputs['sender_id']) && is_numeric($inputs['sender_id'])) {
switch($inputs['sender_type']) {
case 'SystemUser':
return SystemUser::find($inputs['sender_id']);
case 'Customer':
return Customer::find($inputs['sender_id']);
default:
return null;
}
}
}
private function getReceiver($inputs)
{
if(isset($inputs['receiver_type'], $inputs['receiver_id']) && is_numeric($inputs['receiver_id'])) {
switch($inputs['receiver_type']) {
case 'SystemUser':
return SystemUser::find($inputs['receiver_id']);
case 'Customer':
return Customer::find($inputs['receiver_id']);
default:
return null;
}
}
}
private function getTopic($inputs)
{
if(isset($inputs['topic_type'], $inputs['topic_id']) && is_numeric($inputs['topic_id'])) {
switch($inputs['topic_type']) {
case 'Illustrate':
return Illustrate::find($inputs['topic_id']);
default:
return null;
}
}
}
聊天
public function get($id) {
$chat = Chat::find($id);
$sender = $chat->sender;
// Inverse
// $systemUser = SystemUser::find($id);
// $systemUser->sentChats->where('id', $chatId);
$receiver = $chat->receiver;
// Inverse
// $customer = Customer::find($id);
// $customer->receivedChats->where('id', $chatId);
$topic = $chat->topic;
// Inverse
// $illustrate = Illustrate::find($id);
// $illustrate->chats;
}
注意:-请理解我还没有测试过这些...这只是一个关于如何完成工作的小例子。
如果您在理解这一点时遇到任何问题,请告诉我。