我正在努力设置我的消息传递数据库。我允许用户通过我的网站互相发送消息。当用户转到其消息面板时,我希望数据库返回这样的数据
1[
Message with sender_id = 1 and sent_to_id = 2 body = text here
Message with sender_id = 2 and sent_to_id = 1 body = text here
Message with sender_id = 1 and sent_to_id = 2 body = text here
]
2[
Message with sender_id = 1 and sent_to_id = 4 body = text here
Message with sender_id = 4 and sent_to_id = 1 body = text here
]
3[
Message with sender_id = 16 and sent_to_id = 1 body = text here
Message with sender_id = 1 and sent_to_id = 16 body = text here
]
我开始这样创建数据库
$table->bigIncrements('id');
$table->unsignedBigInteger('sender_id');
$table->unsignedBigInteger('sent_to_id');
$table->text('body');
$table->timestamps();
$table->foreign('sender_id')
->references('id')->on('users')
->onDelete('cascade');
$table->foreign('sent_to_id')
->references('id')->on('users')
->onDelete('cascade');
然后使用我的用户模型
public function received()
{
return $this->hasMany(Message::class, 'sent_to_id');
}
public function sent()
{
return $this->hasMany(Message::class, 'sender_id');
}
效果很好,但我看不到像第一个示例那样将消息分组为用户之间的对话的方法。
我是否为要达到的目的正确设置了数据库?
我将如何在模型中进行设置以返回按用户之间的对话分组的消息?
您可以使用conversations
和sender_id
创建一个recipient_id
表以及一个单独的messages
表来存储属于该会话的消息。
/** Conversations **/
class Conversation extends Model
{
protected $fillable = ['sender_id', 'sent_to_id'];
public function messages()
{
return $this->hasMany(Message::class);
}
...
/** Messages **/
class Message extends Conversation
{
protected $fillable = [
'user_id',// User that created this message
'message', // Body of the message
'conversation_id'
];
public function conversation()
{
return $this->belongsTo(Conversation::class);
}
...
通过以上设置,您可以与消息进行对话:
/** Currently authenticated user **/
$userId = auth()->id();
$conversations = App\Conversation::where('sender_id', $userId)
->orWhere('sent_to_id', $userId)
->with('messages')->get();
您可以创建包含以下内容的消息表:
/** Messages **/
class Message extends Model
{
protected $fillable = [
'sender_id',
'receiver_id',
'body',
'seen_at',
];
}
并使用:]进行检索
// don't forget to update seen attribute while fetching App\Message::where('receiver_id',$userId)->update(['seen_at' => date('Y-m-d H:i:s') ]); // $userId = auth::user()->id(); // authenticated_user $messages = App\Message::where('sender_id', $userId)->orWhere('receiver_id',$userId)->get();
并且您可以轻松地对其进行映射以对其进行样式设置(在视图上)
@foreach($messages as $message)
@if ($message->sender_id == Auth::user()->id)
<p class='message_sent'> {{$message->body}} </p>
@else
<p class='message_received'> {{$message->body}} </p>
@endif
@if ($message->seen_at)
<p> {{$message->seen_at}} </p>
@endif
@endforeach