I am trying to build a messaging/chat system. which can store conversation between two people in a chronological order. Also if User A deletes the conversation User B still should have access the conversation until he wishes to delete them.
Inbox - All the messages recieved by the user from various users will be displayed with the latest message from that particular thread.
Conversation Screen - Chronological order of the conversation between the User A and User B
This is the basic structure of the database i have come up with. Should i store the messages twice in the database ?
MySQL is pretty mature. It's capable of storing and handling millions and millions of rows. NoSQL databases aren't magically more performant than relational databases.
I think it's hard to say that one database or another is the BEST without understanding more about the application but rest assured that MongoDB has been the choice for many popular chat applications.
You can store message by message in the DB having send to, send from and date time like fields, meaning one message per record. Or you can also save session based message history at once per record, and it may contain several messages per record.
I would use a lookup table for the messages that would store who has the rights to view that message
table->message | table->messageUsers
id->0, message->'hi', user_id->1 user_id->1, message_id->0
user_id->2, message_id->0
That way if a user deletes their message they are actually just deleting their relationship to the message not the message itself. you just remove them from the messageUsers table. or set a active field to 1 or 0.
At first I thought that when one person deleted it you could just turn either To or From to null but that would make you lose who sent the message or to whom it was addressed.
You should just add a field deleted_by which will contain the id of the person who deleted it or will be null. So when selecting records from the inbox you have something like:
Select * From Messages where to_id = MyID and deleted_by <> MyID
when you delete the message you check if the deleted_by is null, if it is you update the deleted_by field with MyID, if it is not (means that the other party deleted it as well) you delete the record.
If you want to have the same functionality for threads instead of messages (i.e. manage the conversation and not one message at a time) you should have another table (MessageThreads) in which you have the from_id, to_id fields, deleted_by along with a thread_id field. in the Messages table you subsitute the from_id to_id and deleted_by with the thread_id.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With