Just to clear up a potential source of confusion: For Craft, the only 'real' parent-child relationships are the hierarchies in Structures (a type of Section). Entry fields and by extension relations (including the relatedTo
parameter) are technically many-to-many relations (even if you allow only one related entry in your recommendedSystem
field).
The relatedTo
parameter only exists for queries, you can't use it on an Entry model.
Your second approach is the correct one, you can programmatically set field values using craft\elements\Entry::setFieldValue. For entries fields, you need to pass an array of IDs. Also, make sure to save the element using the craft\services\Elements::saveElement to persist your changes in the database.
$model->setFieldValue('recommendedSystem', [$entry->id]);
Craft::$app->elements->saveElement($model);
If it's still not working: The saveElement
method will run validation on the passed element by default and return a boolean to indicate success or failure. Afterwards, you can access any validation errors on the model using $model->getErrors()
. If the field is not getting saved and you're not sure why, try dumping the output to find any errors that prevent the model from saving:
$success = Craft::$app->elements->saveElement($model);
if (!$success) {
Craft::dd($model->getErrors());
}
If you really want to, you can also just save the entry without validation like this:
Craft::$app->elements->saveElement($model, false);
As a sidenote, if $entry
and $model
are the same entry, make sure to check the following checkbox in the settings of the recommendedSystem
field: Allow self relations
Without this option, elements aren't allowed to relate to themselves, so trying to relate an element to itself through an entries field will silently fail.