I'm building a CMS blog with MVC and want users to leave comments on posts.
There are two types of users, users with accounts, and guest users that are not registered.
I am laying out the comment table that looks like this:
CREATE TABLE IF NOT EXISTS `mydb`.`comment` (
`id` INT NOT NULL AUTO_INCREMENT ,
`post_id` INT NOT NULL ,
`user_id` INT NULL ,
`username` VARCHAR(100) NOT NULL ,
`email` VARCHAR(255) NOT NULL ,
`content` TEXT NOT NULL ,
`createtime` DATETIME NOT NULL ,
`approved` TINYINT NOT NULL DEFAULT 0 ,
PRIMARY KEY (`id`) ,
INDEX `FK_comment_user` (`user_id` ASC) ,
INDEX `FK_comment_post` (`post_id` ASC) ,
CON开发者_C百科STRAINT `FK_comment_user`
FOREIGN KEY (`user_id` )
REFERENCES `mydb`.`user` (`id` )
ON DELETE NO ACTION
ON UPDATE CASCADE,
CONSTRAINT `FK_comment_post`
FOREIGN KEY (`post_id` )
REFERENCES `mydb`.`post` (`id` )
ON DELETE NO ACTION
ON UPDATE CASCADE)
ENGINE = InnoDB;
You can see user_id FK is not required because it could be a guest, before saving/validating, I can check to see if the model has a user_id, if so, I can grab the required data: username, email from the user table and inject into this comment model to validate the model.
My question is this: username and email will be redundant data if the user is registered. Also, if they update their email, I'd have to write custom code to cascade this change to this field in the comment. Therefore, would it be better to not require (drop NOT NULL) username and email?
You could have just username, with the implicit understanding that it is an email address, or vice-versa. It's a common thing nowadays to use the two interchangeably.
Theoretically, you could also make a "stub" user for everyone who comments, with an autoincrement id and an email address... then you could keep the comments table only referencing a user id.
精彩评论