Answers.Body: <p>Apparently this is the right way to do it:</p>
  
  <pre><code>$user = User::find()-&gt;username($username)-&gt;one();
  Craft::$app-&gt;users-&gt;assignUserToGroups($user-&gt;id, [1]);
  </code></pre>
  
  <p>It's unclear how <code>setGroups</code> is supposed to work.</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-03-12T20:16:54.943Z
Answers.LastActivityDate: 2020-03-12T20:16:54.943Z
Answers.UserDisplayName: David Jones
Body: <p>The following doesn't assign an existing user to a group. I've confirmed that both the user and the group exist. Any ideas?</p>
  
  <pre><code>$user = User::find()-&gt;username($username)-&gt;one();
  $user-&gt;setGroups([Craft::$app-&gt;userGroups-&gt;getGroupById(1)]);
  Craft::$app-&gt;elements-&gt;saveElement($user);
  </code></pre>
  
  <p>I found <a href="https://craftcms.stackexchange.com/questions/22134/saving-assigning-user-group-via-a-plugin">this answer</a>, which will probably solve it for me, but it leaves me wondering what the purpose of <code>setGroups</code> is.</p>
  
Tags: <user-groups>
Title: How to assign a group to a user in PHP
ThreadText: # How to assign a group to a user in PHP
  
  (Asked by: username_0 on 2020-03-12)
  
  The following doesn't assign an existing user to a group. I've confirmed that both the user and the group exist. Any ideas?
  
  ```
  $user = User::find()->username($username)->one();
  $user->setGroups([Craft::$app->userGroups->getGroupById(1)]);
  Craft::$app->elements->saveElement($user);
  
  ```
  
  I found [this answer](https://craftcms.stackexchange.com/questions/22134/saving-assigning-user-group-via-a-plugin), which will probably solve it for me, but it leaves me wondering what the purpose of `setGroups` is.
  
  **Tags:** user-groups
  
  
  ---
  
  ## 1 answers
  
  ### Answer by username_0 on 2020-03-12. Score: 1
  
  Apparently this is the right way to do it:
  
  ```
  $user = User::find()->username($username)->one();
  Craft::$app->users->assignUserToGroups($user->id, [1]);
  
  ```
  
  It's unclear how `setGroups` is supposed to work.
  
  
  ---
  
  