e304ebdbf50a40879343e5720c9bb6c8f98bf7d9
[yaffs-website] / web / core / modules / system / tests / modules / entity_test / update / entity_definition_updates_8002.inc
1 <?php
2
3 /**
4  * @file
5  * Defines the 8002 db update for the "entity_definition_updates" group.
6  */
7
8 require_once 'entity_definition_updates_8001.inc';
9
10 /**
11  * Makes the 'user_id' field single and migrate its data.
12  */
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();
18
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();
24
25   // Remove data from the storage.
26   $database->truncate('entity_test__user_id')->execute();
27
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);
33
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)
39       ->execute();
40   }
41 }