How to set parent on taxonomy term I have done:

$term = Term::create([
  'name' =&gt; 'title', 
  'vid' =&gt; 'myvocab',
])-&gt;save();


It works.

But I don't seem to be able to set the parent term.

I have tried:

$term-&gt;parent = array($parent_tid);
$term-&gt;save();


It gives an error:


  InvalidArgumentException: Value is not a valid entity. in Drupal\Core\Entity\Plugin\DataType\EntityReference->setValue() (line 106 of /core/lib/Drupal/Core/Entity/Plugin/DataType/EntityReference.php).


I have also tried:

$term-&gt;parents = array($parent_tid);
$term-&gt;save();


It gives no error, but also does nothing.

In my code $term could be a new term or an existing term I've loaded, which is why I set the parent and then save it. But I can't get it to work.

Documentation for D8 is sparse. I've dug around the code in the taxonomy module, and it looks like parent is an entity reference field that accepts multiple values, but I can't work out how to set it. It looks like setting parent to array($id) should work, but I think the magic setter is breaking. Any help?
The correct way for a reference field is to set the property target_id:

$term-&gt;parent = ['target_id' =&gt; '2'];


All this shorter versions work too:

$term-&gt;parent = ['2'];
$term-&gt;parent = '2';
$term-&gt;parent = 2;


Also works like this:

$term-&gt;set('parent', ['target_id' =&gt; 2]);
$term-&gt;set('parent', 2);