I am struggling to setup my messaging database. I am allowing users to message each other through my site. When a user goes to their message panel I want the database to return data like this
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
]
I started creating my database like this
$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');
Then in my user model I have
public function received()
{
return $this->hasMany(Message::class, 'sent_to_id');
}
public function sent()
{
return $this->hasMany(Message::class, 'sender_id');
}
which works great but it I can't see a way to group the messages into conversations between users like my first example.
Did I setup my database correctly for what I am trying to achieve?
How would I set it up in my model to return messages grouped by conversation between users?