Saving matrix field of a duplicate of an entry not working I'm creating a cron job to automatically import new entries (vacancies).
I have an entry that I use as a template with some standard data fields and matrix fields. If it's an entry that has not been imported before I create a new entry as a duplicate of the template entry.
$entry = Craft::$app-&gt;getElements()-&gt;duplicateElement($entryTemplate);

The template already has the matrix blocks but only placeholder data that I want to overwrite like this:
// existing matrix fields (already created or from template)
$matrixBlocks = $entry-&gt;myMatrixBlock;

/** @var MatrixBlock $matrixBlock */
foreach($matrixBlocks as $matrixBlock) {
    $matrixBlock-&gt;setFieldValues(['contactText' =&gt; 'random text']);

    $success = Craft::$app-&gt;elements-&gt;saveElement($matrixBlock);
}

The strange thing is that the ownerId of the matrixBlock isn't the value of the $entry-&gt;id nor is it the value of the template id. It generated a new ownerId.
It works correctly when I import it a second time because the owner id is now correct.
This sounds suspiciously like a bug that was fixed in today's Craft 3.6.10 release.

Fixed a bug where entries could return the wrong Matrix/Neo/Super Table blocks if the blocks were queried immediately after the entry was created via craft\services\Elements::duplicateElement().

My guess is if you update to that release, it'll behave like you expect now.