Kohana Many-to-Many Success … Finally
I finally got somewhere with my little piece of Kohana v2.3 code. I’m using two tables ‘users’ and ‘roles’ and also have the required pivot table ‘roles_users’ as I want to be able to associate particular users with multiple roles. For example, Bob could be ‘admin’ and ‘editor’ but Jane could also be an ‘admin’. After struggling with non-existent methods and deprecated functions I finally got it to work. This is only a snippet of the code and it’s only basic but shows how to do it. I hope somebody finds it useful.
$user = new User_Model();
$user->username = $form['username'];
$user->password = $user->hash_password ($form['password'], $user->salt);
$user->last_login = time();
$user->logins = 1;
$role = new Role_Model;
The code creates a new user in the database with their selected username and password. It then automatically assigns them the ‘admin’ role.
The code isn’t practical in any way as it assumes all validation has been completed, i.e. that the username is permissible, unique and the password is set according to the policies of the site. You’re also not going to automatically assign an ‘admin’ right to a newly registered user but I was just playing with how to establish a object relationship.