Version 1
[yaffs-website] / web / core / modules / system / tests / modules / entity_test / update / entity_definition_updates_8001.inc
1 <?php
2
3 /**
4  * @file
5  * Defines the 8001 db update for the "entity_definition_updates" group.
6  */
7
8 use Drupal\Core\Field\FieldStorageDefinitionInterface;
9
10 /**
11  * Makes the 'user_id' field multiple and migrate its data.
12  */
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();
18
19   // Retrieve existing field data.
20   $user_ids = $database->select('entity_test', 'et')
21     ->fields('et', ['id', 'user_id'])
22     ->execute()
23     ->fetchAllKeyed();
24
25   // Remove data from the storage.
26   $database->update('entity_test')
27     ->fields(['user_id' => NULL])
28     ->execute();
29
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);
35
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]);
41   }
42   $insert_query->execute();
43 }