How to assign a group to a user in PHP 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()-&gt;username($username)-&gt;one();
$user-&gt;setGroups([Craft::$app-&gt;userGroups-&gt;getGroupById(1)]);
Craft::$app-&gt;elements-&gt;saveElement($user);


I found this answer, which will probably solve it for me, but it leaves me wondering what the purpose of setGroups is.
Apparently this is the right way to do it:

$user = User::find()-&gt;username($username)-&gt;one();
Craft::$app-&gt;users-&gt;assignUserToGroups($user-&gt;id, [1]);


It's unclear how setGroups is supposed to work.