I was having a weird bug with my views. Some entity-references from my main-entity didn't show up in my view.
I investigated further with entityQuery and came across some weird action. I can get the missing referenced entities by querying for nulls in main_entity and loading the referenced entities manually using the magic entity getter:
// Returns 90 main-entities. These correspond to the entities with missing data in my view.
$main_entity_ids = \Drupal::entityQuery('main_entity')
->notExists('field_referenced_entity')
->sort('created')
->execute();
$main_entities = \Drupal\my_module\Entity\MainEntity::loadMultiple($main_entity_ids);
// Load referenced entities for each main entity using the magic entity getter
$referenced_entities = [];
foreach($main_entities as $main_id => $main_entity){
// Skip nulls
if($referenced_entity = $main_entity->get('field_referenced_entity')->entity){
$referenced_entities[$referenced_entity->id()] = $referenced_entity;
// // Re-saving the entity here doesn't help
// $main_entity->set('field_referenced_entity', $referenced_entity->id())
// $main_entity->save();
}
}
// At this point $referenced_entities -array contains 90 fully loaded refenced entities.
Also, the table main_entity__field_referenced_entity is missing rows for the missing references. I wonder how am I able to get the reference with the magic getter.
I tried to re-save all the entities in my loop but with no success.
The main-entity is first created and saved without the reference which is added afterwards inside ContentEntityForm::save()-method.
...
// Entity is saved and re-loaded
$main_entity->save();
$main_entity = \Drupal\my_module\Entity\MainEntity::load($id);
...
// Set the reference and save
$main_entity->set('field_referenced_entity', 123);
$main_entity->save();
...
Creating the MainEntity programmatically seems to work, inserting the required rows to the main_entity__field_referenced_entity -table:
$main_entity = \Drupal\my_module\Entity\MainEntity::create([
'type' => 'main_entity',
'status' => 1,
'name' => 'Programmatically created MainEntity',
]);
$main_entity->save(); // No rows
$main_entity = \Drupal\my_module\Entity\MainEntity::load($main_entity->id());
$main_entity->set('field_referenced_entity', 123);
$main_entity->save(); // Row added
The problem seems to have started after updating to Drupal 8.5 from 8.4.4. I was running Drupal 8.5.3 when I noticed the problem. Updating to Drupal 8.5.5 doesn't help.
Does anyone have any idea what could be going on?