Add an entity reference to a user I'm attempting to programmatically create test users in Drupal 8 via  hook_update_n(). I have an array of user attributes I'm using to create users.

I've got three fields added to the User entity that add term references to existing vocabularies that have been populated with terms. Two of these fields store a single term reference, while the third can store multiple term references.

I've retrieved the term object using this code.

    $term = \Drupal::entityTypeManager()
        -&gt;getStorage('taxonomy_term')
        -&gt;loadByProperties(['name' =&gt; $user['bu'], 'vid' =&gt; 
    'tx_business_unit']);


I'm trying to add a term reference to my user field, called "user_bu".

I've attempted to use the solution given on Programmatically update an entity reference field, but it doesn't work for me.

Everything else on my user record is being populated without issue.
For those of you who may be looking to answer the same question, here's how I got it to work in my case (I'm working on a Drupal 8.3 site):

$users = [
  'test_local_contributor' =&gt; [
    'password' =&gt; '1testme1',
    'langcode' =&gt; $language,
    'preferred_langcode' =&gt; $language,
    'email' =&gt; 'test_local_contributor@example.com',
    'roles' =&gt; [
      'employee',
      'local_contributor',
      'testuser',
    ],
    'location' =&gt; [
      'Kentucky',
      'Paradise',
    ],
    'sbu' =&gt; 'energy',
    'bu' =&gt; 'natural_gas',
  ],
  ...(there were other test users, omitted for brevity)
];

foreach ($users as $key =&gt; $user) {
  $newUser = User::create();
  $newUser-&gt;setUsername($key);
  $newUser-&gt;setPassword($user['password']);
  $newUser-&gt;enforceIsNew();
  $newUser-&gt;setEmail($user['email']);
  $newUser-&gt;set('langcode', $user['langcode']);
  $newUser-&gt;set('preferred_langcode', $user['langcode']);
  foreach ($user['roles'] as $role) {
    $newUser-&gt;addRole($role);
  }
  $newUser-&gt;set('status', 1);

  if (isset($user['bu'])) {
    $term = \Drupal::entityTypeManager()
      -&gt;getStorage('taxonomy_term')
      -&gt;loadByProperties(['name' =&gt; $user['bu'], 'vid' =&gt; 'tx_business_unit']);
    $keys = array_keys($term);
    $newUser-&gt;set('user_bu', $keys);
  }

  if (isset($user['sbu'])) {
    $term = \Drupal::entityTypeManager()
      -&gt;getStorage('taxonomy_term')
      -&gt;loadByProperties(['name' =&gt; $user['sbu'], 'vid' =&gt; 'tx_sbu']);
    $keys = array_keys($term);
    $newUser-&gt;set('user_sbu', $keys);
  }

  $loc_keys = array();
  foreach ($user['location'] as $location) {
    $newkeys = array();
    $term = \Drupal::entityTypeManager()
      -&gt;getStorage('taxonomy_term')
      -&gt;loadByProperties(['name' =&gt; $location, 'vid' =&gt; 'tx_user_location']);
    $keys = array_keys($term);
    $newkeys = array_merge($loc_keys, $keys);
    $loc_keys = $newkeys;
  }
  $newUser-&gt;set('user_location', $loc_keys);

  $result = $newUser-&gt;save();
}