I also solved this task. I think one table it is not useful in this case. So, i suggest use 2 tables:
CREATE TABLE `message` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`subject` varchar(255) NOT NULL,
`body` text NOT NULL,
`date` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `message_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`message_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`interlocutor` int(11) DEFAULT NULL,
`folder` enum('inbox','sent') NOT NULL,
`starmark` tinyint(1) NOT NULL DEFAULT '0',
`unread` tinyint(1) NOT NULL DEFAULT '1',
`deleted` enum('none','trash','deleted') NOT NULL DEFAULT 'none',
PRIMARY KEY (`id`),
CONSTRAINT `message_user_user_fk_1` FOREIGN KEY (`message_id`) REFERENCES `message` (`id`) ON UPDATE CASCADE,
CONSTRAINT `message_user_user_fk_2` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON UPDATE CASCADE,
CONSTRAINT `message_user_user_fk_3` FOREIGN KEY (`interlocutor`) REFERENCES `user` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
I think it can fix all of your issues, because message users separated from each other
So, for one message we must create 3 inserts like this:
public static function createMessage($subject, $body, $source, $sender_id, $receiver_id)
{
// save DATA to message table ($subject, $body, $source)
// save DATA to message_user table ($message_id, $sender_id, $receiver_id, 'sent')
// save DATA to message_user table ($message_id, $receiver_id, $sender_id, 'inbox')
}
In this case for every user we create separated row in table message_user. So, when user_1 delete message in this inbox folder we mark it as 'deleted' and has no effect on the second user.
So, that get all user messages we must run only simple SELECT like this:
SELECT *
FROM message m
JOIN message_user mu
ON m.id = mu.message_id
WHERE mu.deleted = 'none'
AND mu.user_id = :user_id