I am designing a database that will keep track of users and their relationship with different organizations. A user can belong to many organizations, and an organization can have many users. That part is simple to solve with a Many to Many relationship. However, where things get a little more fuzzy is that a user can also be an admin to one or more of the organizations, and a user needs to be able to log time spend with each organization.
It seems that there are many ways to solve this. Here is the table structure I have so far, I would like your opinion if you think there is a better way.
CREATE TABLE `organization` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL COLLATE 'utf8_unicode_ci',
PRIMARY KEY (`id`)
);
CREATE TABLE `user` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`first_name` VARCHAR(50) NOT NULL COLLATE 'utf8_unicode_ci',
`last_name` VARCHAR(50) NOT NULL COLLATE 'utf8_unicode_ci',
`email` VARCHAR(50) NOT NULL COLLATE 'utf8_unicode_ci',
`password` VARCHAR(255) NOT NULL COLLATE 'utf8_unicode_ci',
PRIMARY KEY (`id`),
UNIQUE INDEX `email` (`email`)
);
CREATE TABLE `time_log` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`user_organization_id` INT(11) NOT NULL,
`date` DATE NOT NULL,
`time` TINYINT(4) NOT NULL,
PRIMARY KEY (`id`),
INDEX `user_organization_id` (`user_organization_id`),
CONSTRAINT `fk_time_log_user_organization` FOREIGN KEY (`user_organization_id`) REFERENCES `user_organization` (`id`)
);
CREATE TABLE `user_organization` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`user_id` INT(11) NOT NULL,
`organization_id` INT(11) NOT NULL,
`admin` TINYINT(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`, `user_id`, `organization_id`, `admin`) USING BTREE,
INDEX `user_id` (`user_id`),
INDEX `organization_id` (`organization_id`),
CONSTRAINT `fk_user_organization_organization` FOREIGN KEY (`organization_id`) REFERENCES `organization` (`id`),
CONSTRAINT `fk_user_organization_user` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`)
);
I chose to go with an id
field on the user_organization
table because it made creating a foreign key to the time_log
table easier. However, I could also just put the user_id
, and organization_id
in the time_log table
as well.