5 * Defines the 8002 db update for the "entity_definition_updates" group.
8 require_once 'entity_definition_updates_8001.inc';
11 * Makes the 'user_id' field single and migrate its data.
13 function entity_test_update_8002() {
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 entity data.
20 $query = $database->select('entity_test__user_id', 'et')
21 ->fields('et', ['entity_id', 'user_id_target_id']);
22 $query->condition('et.delta', 0);
23 $user_ids = $query->execute()->fetchAllKeyed();
25 // Remove data from the storage.
26 $database->truncate('entity_test__user_id')->execute();
28 // Update definitions and schema.
29 $manager = \Drupal::entityDefinitionUpdateManager();
30 $storage_definition = $manager->getFieldStorageDefinition('user_id', 'entity_test');
31 $storage_definition->setCardinality(1);
32 $manager->updateFieldStorageDefinition($storage_definition);
34 // Restore entity data in the new schema.
35 foreach ($user_ids as $id => $user_id) {
36 $database->update('entity_test')
37 ->fields(['user_id' => $user_id])
38 ->condition('id', $id)