How do I programmatically create a node with an entity reference (to an user)? It is kind of strange because my code creates the node with the referenced user uid in node_field_data, but when I open this node the user reference isn't working. Then I navigated the database and found that, when I update the user reference field in the interface, it is also written as a new registry in the table node__field_user, so I guess I should insert it there too.

But, I don't know how to do this with the API, and I think making it with a SQL query probably means security issues and is probably much more complicated than however it can be done with the API.

This is my code:

  $node = Node::create(['type' =&gt; 'nodetype']);
  $node-&gt;set('title', $username );
  $node-&gt;uid-&gt;entity = $userId;
  $node-&gt;enforceIsNew();
  $node-&gt;save();
Set owner $node-&gt;setOwnerId($uid);

Set field reference $node-&gt;field_user[] = $uid;