2
$groupIds = [1, 2];
craft()->userGroups->assignUserToGroups($user, $groupIds);

When executed I get the following error:

CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity     constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`letshacklondon2016`.`craft_usergroups_users`, CONSTRAINT `craft_usergroups_users_userId_fk` FOREIGN KEY (`userId`) REFERENCES `craft_users` (`id`) ON DELETE CASCADE). The SQL statement executed was: INSERT INTO `craft_usergroups_users` (`groupId`, `userId`, `dateCreated`, `dateUpdated`, `uid`) VALUES (:row0_col0, :row0_col1, :row0_col2, :row0_col3, :row0_col4), (:row1_col0, :row1_col1, :row1_col2, :row1_col3, :row1_col4). Bound with :row0_col0=1, :row0_col1=Craft\UserModel::__set_state(array('elementType' => 'User', ... (etc.)

Any Ideas?

1

UserGroupsService->assignUserToGroups takes a user's ID as the first parameter and you're passing in the entire UserModel.

Change it to this and it should work:

craft()->userGroups->assignUserToGroups($user->id, $groupIds); 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.