Creating group content is always a 2 step process but this makes for a confusing UX. I'm trying to do it all in one step, but running into this problem.
function hook_myEntity_insert($myEntity) {// also update
$group = Group::load(99);
$props = [
'type' => $group->getGroupType()->id().'-my_plugin-'.$myEntity->bundle(),
'gid' => $group->id(),
'entity_id' => $myEntity->id(),
];
GroupRelationship::create($props)->save();
}
This falls into a recursive loop when GroupRelationship::postsave() calls $this->getEntity()->save().
Furthermore if I user hook_ENTITY_TYPE_update, the $myEntity passed through the loop is the original entity, not the updated one.
The script explains why
// We want to make sure that the entity we just added to the group behaves
// as a grouped entity. This means we may need to update access records,
// flush some caches containing the entity or perform other operations we
// cannot possibly know about. Lucky for us, all of that behavior usually
// happens when saving an entity so let's re-save the added entity.
I tried moving that function to drupal_register_shutdown_function(), before realising it just falls into the same loop.
So please, manually do those operations you cannot possibly know about, and don't deny us the possibility of making a good user experience.