Hi folks,

I am posting this in the hope that some of you may be able to help.

I have a User model which has a HABTM association to Role and vice
versa.

I would like to add role to a user in the following way:


Tables:
        users: fields..., HABTM Role
        roles: id,name    -- HABTM User
        roles_users : user_id,role_id (linking table)

Code:
        $role = array();
        $role['Role'] = array('id' => $role_id);
        $role['User']['User'] = array($list_user_id);
        $this->User->Role->create();
        $this->User->Role->save($role); // the role should really be updated
only and the association added to the user

Failed: Cake has thrown the following error: Warning (512): SQL Error:
1054: Unknown column 'RolesUser.id' in 'field list' [CORE\cake\libs
\model\datasources\dbo_source.php, line 521]

Cannot figure out what the problem really is, do not even know why
cake is looking at that field.

Because that fails I was forced to write a function to add roles to
user, which in my opinion is ugly.

Function:
//Send in the user id and role name
//function declared in user.php model
function addRole($user_id,$role){
        $this->expects(array('Role')); //Models are binding when needed only
        //$params = array('conditions' => array( 'Role.name' => $role));
        $this->Role->recursive = -1;
        $role = $this->Role->findByName($role);
        $role_id = $role['Role']['id'];
        if(!$data = $this->Role->query("SELECT * FROM roles_users AS Role
WHERE role_id = $role_id AND user_id = $user_id")){
                //$role['User'] = array('User' => array($user_id));
                //$this->Role->save($role); //Not working, errors for some 
reason
                //pr('Please save the role now');
                $this->Role->query("INSERT INTO roles_users (user_id,role_id) 
VALUES
($user_id,$role_id)");
        }
}

That works, but I would like to avoid that if possible.

Do any of you know a smarter way to do the job.

Many thanks in advance...







--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"CakePHP" group.
To post to this group, send email to cake-php@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/cake-php?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to