So, In my project there are groups and users. Each users belongs to a group, and one of those users is also an Admin of the group. I have been struggling to figure out how to map those relationships.
Currently with the set up I am creating a form that will create a new group, and its admin at the same time (so also a new user).
I want to know how to set this up so A- I can save the user and group correctly and B- So in the form both the user and the group information can be validated and show the errors.
This is the current layout of my DB tables
Groups Table:
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(10) unsigned DEFAULT NULL,
`name` varchar(60) NOT NULL,
`account_active` tinyint(1) DEFAULT NULL,
`create_date` date NOT NULL,
`last_modified` date NOT NULL,
`delete_date` date DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `groups_fk_admin` (`administrator`),
CONSTRAINT `groups_fk_admin` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)
And the Users Table:
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`group_id` int(10) unsigned DEFAULT NULL,
`email` varchar(200) NOT NULL,
`password` varchar(40) NOT NULL,
`first_name` varchar(45) NOT NULL,
`last_name` varchar(45) NOT NULL,
`create_date` date NOT NULL,
`last_modified` date NOT NULL,
`delete_date` date DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`),
KEY `users_group_id_fk` (`group_id`),
CONSTRAINT `users_group_id_fk` FOREIGN KEY (`group_id`) REFERENCES `groups` (`id`)
Then my models are currently setup like….
Group Model:
public $hasMany = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'group_id',
'dependent' => false,
)
);
public $belongsTo = array(
'Administrator' => array(
'className' => 'User',
'foreignKey' => 'user_id',
)
);
Users Model:
public $hasMany = array(
'Admin' => array(
'className' => 'Group',
'foreignKey' => 'user_id',
'dependent' => false,
),
);
public $belongsTo = array(
'Group' => array(
'className' => 'Group',
'foreignKey' => 'group_id',
)
);
Thank you for your help! And let me know if I can provide any more information.
Group hasMany User
User belongsTo Group
And just add another column to the Users table called is_admin or whatever, with the value of the ID of the group it is admin of.
For certain actions you should simply check if it passes a certain condition. So if you want to check if a user is an administrator of group 4, it has to check if it’s is_admin id is equal to 4. You could set to 0 for ‘normal’ users.
Being a property of a user, administrator shouldn’t be declared in your DB relation with a User hasMany admin and a group belongsTo admin, admin isn’t a model on its own. It is a property of User, a role.