How to add email address to User programatically?

Hello. I am writing a custom REST API to push users from another product of ours into CRM (on premise, not sugar cloud). The code that handles saving or editing the user is the following:

private function processUserBean($user_bean,string $user_name,string $user_hash,string $first_name,string $last_name,string $title,string $email,int $is_admin,string $status):void
{
 $user_bean->user_name=$user_name;
 $user_bean->first_name=$first_name;
 $user_bean->last_name=$last_name;
 $user_bean->title=$title;
 $user_bean->status=$status;
 $user_bean->is_admin=$is_admin;
 $user_bean->user_hash=$user_hash;
 if (!empty($email))
 {
  $user_bean->emailAddress->addAddress($email);
 }
 $user_bean->save();
}

Every forum and documentation directs me to this ->emailAddress->addAddress approach. This ALMOST works. What happens is the following: The User is created correctly in the database (record in users table), the email address is created correctly (record in email_addresses table) BUT the link between them, a record in email_addr_bean_rel table is NOT CREATED. What am I doing wrong?

Parents Reply Children