5 * Defines the 8001 db update for the "entity_definition_updates" group.
8 use Drupal\Core\Field\FieldStorageDefinitionInterface;
11 * Makes the 'user_id' field multiple and migrate its data.
13 function entity_test_update_8001() {
14 // To update the field schema we need to have no field data in the storage,
15 // thus we retrieve it, delete it from storage, and write it back to the
16 // storage after updating the schema.
17 $database = \Drupal::database();
19 // Retrieve existing field data.
20 $user_ids = $database->select('entity_test', 'et')
21 ->fields('et', ['id', 'user_id'])
25 // Remove data from the storage.
26 $database->update('entity_test')
27 ->fields(['user_id' => NULL])
30 // Update definitions and schema.
31 $manager = \Drupal::entityDefinitionUpdateManager();
32 $storage_definition = $manager->getFieldStorageDefinition('user_id', 'entity_test');
33 $storage_definition->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
34 $manager->updateFieldStorageDefinition($storage_definition);
36 // Restore entity data in the new schema.
37 $insert_query = $database->insert('entity_test__user_id')
38 ->fields(['bundle', 'deleted', 'entity_id', 'revision_id', 'langcode', 'delta', 'user_id_target_id']);
39 foreach ($user_ids as $id => $user_id) {
40 $insert_query->values(['entity_test', 0, $id, $id, 'en', 0, $user_id]);
42 $insert_query->execute();