Home > Uncategorized > Kohana Many-to-Many Success … Finally

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;
$role->where('name', 'admin')->find();
$user->add ($role);
$user->save();

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.

Categories: Uncategorized Tags:
  1. Roy
    November 15, 2009 at 8:16 pm

    Hi

    I am so glad I found this post.

    I don’t really understand it though. Could you explain the part where you add the $role.

    Thnx

  2. David
    March 27, 2010 at 4:34 pm

    Would be nice to see the models…

    Also, how would you then find all the users with a particular role…

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: