3

because we have a lot of query on created date field on our custom Entity, we looking for a solution to index 'created' field index in Mysql.

this is our baseFieldDefinition :

public static function baseFieldDefinitions(EntityTypeInterface $entity_type) { $fields = parent::baseFieldDefinitions($entity_type);

$fields['product_id'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Product Category'))
  ->setDescription(t('Product Category ref'))
  ->setRevisionable(FALSE)
  ->setSetting('target_type', 'taxonomy_term');

$fields['site_id'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Site ID Ref'))
  ->setDescription(t('Site Category ref'))
  ->setRevisionable(FALSE)
  ->setSetting('target_type', 'taxonomy_term');


$fields['price'] = BaseFieldDefinition::create('integer')
  ->setLabel(t('Price'))
  ->setDescription(t('The Price of the Crawl entity entity.'))
  ->setDefaultValue(0);

$fields['created'] = BaseFieldDefinition::create('created')
  ->setLabel(t('Created'))
  ->setDescription(t('The time that the entity was created.'));

return $fields;

}

enter image description here

is there any setting or method in ContentEntityBase to set a field indexable in Mysql?

NOTE: we can index it with a simple migration in our module installer but first of it I'm curious about it, is there any solution to achieve it in BaseFieldDefinition?

1
  • 1
    It seems like it should be possible, there's a comment in BaseFieldDefinition::getSchema(): Merge custom indexes with those specified by the field type. Custom indexes prevail, but there's no method exposed to set the protected $indexes which is a shame
    – Clive
    Jun 8, 2018 at 16:09

1 Answer 1

3

The way to do that at the moment is a custom storage schema handler, see NodeStorageSchema for example:

protected function getEntitySchema(ContentEntityTypeInterface $entity_type, $reset = FALSE) {
  $schema = parent::getEntitySchema($entity_type, $reset);

  $schema['node_field_data']['indexes'] += [
    'node__frontpage' => ['promote', 'status', 'sticky', 'created'],
    'node__title_type' => ['title', ['type', 4]],
  ];

  return $schema;
}

And then you register it with:

"storage_schema" = "Drupal\node\NodeStorageSchema",

as a handler.

To update existing installations, you need to drun drush entup or write an update function.

1

Not the answer you're looking for? Browse other questions tagged or ask your own question.