I have created a messaging system for users, it allows them to send a message to another user. If it is the first time they have spoken then a new conversation is initiated, if not the old conversation continues.
The users inbox lists all conversations the user has had with all other users, these are then ordered by the conversation which has the latest post in it.
A user can only have one conversation with another user.
When a user clicks one of these conversations they are taken to a page showing the whole conversation they've had with newest posts at the top. So it's kind of like a messaging chat functionality.
I have two tables:
- userconversation
- usermessages
userconversation
Contains an auto increment id which is the conversation id, along with the userId and the friendId.
Whoever initates the first conversation will always be userId and the recipient friendId, this will then never change for that conversation.
+----+--------+----------+
| id | userId | friendId |
+----+--------+----------+
usermessages
Contains the specific messages, along with a read flag, the time and conversationId
+----+---------+--------+------+------+----------------+
| id | message | userId | read | time | conversationId |
+----+---------+--------+------+------+----------------+
How it works
When a user goes to message another user, a query will run to check if both users have a match in the userconversation table, if so that conversationId is used and the conversation carries on, if not a new row is created for them with a unique conversationId.
Where it gets complicated
So far all is well, however when it comes to displaying the message inbox of all conversations, sorted on the latest post, it get's tricky t