From 2647c1c4afc4d796f9cebe29f803310121f3d918 Mon Sep 17 00:00:00 2001
From: William Hearn <sylus1984@gmail.com>
Date: Sat, 22 Apr 2017 21:43:01 -0400
Subject: [PATCH] Issue #2496699 by Jelle_S, attiks, deepakaryan1988: Allow
 comments to be attached to entities using a string primary key

---
 core/modules/comment/comment.info.yml              |   1 +
 core/modules/comment/comment.install               |  55 +++++++-
 core/modules/comment/comment.module                |  51 +------
 core/modules/comment/comment.views.inc             |  25 ----
 .../config/optional/views.view.comments_recent.yml |  47 +++++--
 .../comment/migration_templates/d6_comment.yml     |   2 +-
 .../comment/src/CommentAccessControlHandler.php    |   8 +-
 core/modules/comment/src/CommentLazyBuilders.php   |   2 +-
 core/modules/comment/src/CommentManager.php        |  64 ++++++++-
 .../comment/src/CommentManagerInterface.php        |   8 ++
 core/modules/comment/src/CommentStatistics.php     |  23 ++--
 core/modules/comment/src/CommentStorage.php        |  93 ++++++++-----
 core/modules/comment/src/CommentStorageSchema.php  |  55 +++++++-
 core/modules/comment/src/CommentTypeForm.php       |   1 +
 core/modules/comment/src/CommentTypeInterface.php  |   9 ++
 core/modules/comment/src/CommentViewsData.php      |  29 +---
 .../comment/src/Controller/CommentController.php   |   2 +-
 core/modules/comment/src/Entity/Comment.php        |  21 +--
 core/modules/comment/src/Entity/CommentType.php    |   7 +
 core/modules/comment/src/Form/DeleteForm.php       |   2 +-
 .../EntityReferenceSelection/CommentSelection.php  |  10 +-
 .../migrate/destination/EntityCommentType.php      |   1 +
 .../comment/src/Plugin/views/argument/UserUid.php  |   8 +-
 .../src/Plugin/views/field/NodeNewComments.php     |   9 +-
 .../comment/src/Plugin/views/filter/UserUid.php    |   7 +
 .../modules/comment/src/Plugin/views/join/Cast.php | 153 +++++++++++++++++++++
 .../comment/src/Plugin/views/wizard/Comment.php    |  13 +-
 .../modules/comment/src/Tests/CommentAdminTest.php |   4 +-
 core/modules/comment/src/Tests/CommentBookTest.php |   2 +-
 core/modules/comment/src/Tests/CommentCSSTest.php  |   2 +-
 .../comment/src/Tests/CommentCacheTagsTest.php     |   2 +-
 .../comment/src/Tests/CommentLanguageTest.php      |   2 +-
 .../modules/comment/src/Tests/CommentLinksTest.php |   2 +-
 .../comment/src/Tests/CommentNewIndicatorTest.php  |   2 +-
 .../comment/src/Tests/CommentNonNodeTest.php       |   9 +-
 .../modules/comment/src/Tests/CommentTestTrait.php |   2 +
 .../comment/src/Tests/CommentTranslationUITest.php |   2 +-
 core/modules/comment/src/Tests/CommentTypeTest.php |   2 +-
 .../src/Tests/Views/ArgumentUserUIDTest.php        |   2 +-
 .../src/Tests/Views/CommentFieldFilterTest.php     |   3 +-
 .../src/Tests/Views/CommentFieldNameTest.php       |   2 +-
 .../src/Tests/Views/CommentRestExportTest.php      |   2 +-
 .../comment/src/Tests/Views/CommentTestBase.php    |   4 +-
 .../Tests/Views/DefaultViewRecentCommentsTest.php  |   2 +-
 .../comment/src/Tests/Views/FilterUserUIDTest.php  |   2 +-
 .../test_views/views.view.test_comment_rest.yml    |  16 +--
 .../test_views/views.view.test_comment_row.yml     |  47 +++++--
 .../test_views/views.view.test_comment_rss.yml     |  12 +-
 .../test_views/views.view.test_field_filters.yml   |  11 +-
 .../CommentDefaultFormatterCacheTagsTest.php       |   2 +-
 .../tests/src/Kernel/CommentFieldAccessTest.php    |  10 +-
 .../src/Kernel/CommentStringIdEntitiesTest.php     |   4 +-
 .../tests/src/Kernel/CommentValidationTest.php     |   9 +-
 .../tests/src/Kernel/Views/CommentUserNameTest.php |  12 +-
 .../Kernel/Views/CommentViewsFieldAccessTest.php   |  12 +-
 ....field.comment.comment_forum.commented_node.yml |  23 ++++
 .../field.storage.comment.commented_node.yml       |  18 +++
 core/modules/forum/src/ForumIndexStorage.php       |  10 +-
 core/modules/forum/src/ForumManager.php            |   6 +-
 .../forum/src/Tests/Views/ForumIntegrationTest.php |   4 +-
 .../forum/tests/src/Functional/ForumBlockTest.php  |   2 +-
 .../tests/src/Functional/ForumUninstallTest.php    |   2 +-
 .../modules/node/src/Tests/NodeAccessPagerTest.php |   2 +-
 core/modules/rdf/rdf.module                        |  10 +-
 .../rdf/src/Tests/CommentAttributesTest.php        |   2 +-
 .../tests/src/Functional/StandardProfileTest.php   |   2 +-
 .../EntityReferenceSelectionAccessTest.php         |   6 +-
 core/modules/tracker/tracker.module                |   4 +-
 core/modules/views/src/Tests/DefaultViewsTest.php  |   2 +-
 .../views/src/Tests/Entity/FieldEntityTest.php     |   2 +-
 .../views/src/Tests/Handler/HandlerTest.php        |  12 +-
 .../test_views/views.view.test_destroy.yml         |  17 ++-
 .../views.view.test_field_get_entity.yml           |  15 +-
 .../views.view.test_handler_relationships.yml      |  26 ++--
 .../views.view.test_relationship_dependency.yml    |  11 +-
 .../Kernel/Entity/ViewEntityDependenciesTest.php   |   1 +
 .../field.field.comment.comment.commented_node.yml |  23 ++++
 .../field.storage.comment.commented_node.yml       |  18 +++
 78 files changed, 793 insertions(+), 314 deletions(-)
 create mode 100644 core/modules/comment/src/Plugin/views/join/Cast.php
 create mode 100644 core/modules/forum/config/optional/field.field.comment.comment_forum.commented_node.yml
 create mode 100644 core/modules/forum/config/optional/field.storage.comment.commented_node.yml
 create mode 100644 core/profiles/standard/config/install/field.field.comment.comment.commented_node.yml
 create mode 100644 core/profiles/standard/config/install/field.storage.comment.commented_node.yml

diff --git a/core/modules/comment/comment.info.yml b/core/modules/comment/comment.info.yml
index ea529a4..bf78d50 100644
--- a/core/modules/comment/comment.info.yml
+++ b/core/modules/comment/comment.info.yml
@@ -6,4 +6,5 @@ version: VERSION
 core: 8.x
 dependencies:
   - text
+  - entity_reference
 configure: comment.admin
diff --git a/core/modules/comment/comment.install b/core/modules/comment/comment.install
index 47241c2..0539ba9 100644
--- a/core/modules/comment/comment.install
+++ b/core/modules/comment/comment.install
@@ -9,6 +9,8 @@
 use Drupal\Core\StringTranslation\PluralTranslatableMarkup;
 use Drupal\Core\StringTranslation\TranslatableMarkup;
 use Drupal\field\Entity\FieldStorageConfig;
+use Drupal\comment\Entity\CommentType;
+use Drupal\comment\Entity\Comment;
 
 /**
  * Implements hook_uninstall().
@@ -41,10 +43,10 @@ function comment_schema() {
     'description' => 'Maintains statistics of entity and comments posts to show "new" and "updated" flags.',
     'fields' => [
       'entity_id' => [
-        'type' => 'int',
-        'unsigned' => TRUE,
+        'type' => 'varchar_ascii',
         'not null' => TRUE,
-        'default' => 0,
+        'default' => '0',
+        'length' => 255,
         'description' => 'The entity_id of the entity for which the statistics are compiled.',
       ],
       'entity_type' => [
@@ -184,3 +186,50 @@ function comment_update_8301() {
   $entity_type->set('entity_keys', $keys);
   $definition_update_manager->updateEntityType($entity_type);
 }
+
+/**
+ * Update existing comments to use the new entity reference fields.
+ */
+function comment_update_8302(&$sandbox) {
+  if (!isset($sandbox['total'])) {
+    $definition_update_manager = \Drupal::entityDefinitionUpdateManager();
+    $entity_type = $definition_update_manager->getEntityType('comment');
+    $definition_update_manager->updateEntityType($entity_type);
+
+    // Update the statistics entity_id field.
+    db_change_field(
+      'comment_entity_statistics',
+      'entity_id',
+      'entity_id',
+      [
+        'type' => 'varchar_ascii',
+        'not null' => TRUE,
+        'default' => '0',
+        'length' => 255,
+        'description' => 'The entity_id of the entity for which the statistics are compiled.',
+      ]
+    );
+    $sandbox['total'] = $query = \Drupal::entityQuery('comment')->count()->execute();
+    $sandbox['current'] = 0;
+  }
+  $cids = db_select('comment_update_8302', 'c')
+    ->fields('c', ['cid', 'entity_id'])
+    ->orderBy('cid')
+    ->range($sandbox['current'], 50)
+    ->execute()
+    ->fetchAllKeyed();
+
+  foreach ($cids as $cid => $entity_id) {
+    $comment = Comment::load($cid);
+    $comment->set(CommentType::load($comment->bundle())->getEntityReferenceFieldName(), $entity_id);
+    $comment->save();
+  }
+  $sandbox['current'] += 50;
+  if ($sandbox['current'] >= $sandbox['total']) {
+    db_drop_table('comment_update_8302');
+    $sandbox['#finished'] = 1;
+  }
+  else {
+    $sandbox['#finished'] = $sandbox['current'] / $sandbox['total'];
+  }
+}
diff --git a/core/modules/comment/comment.module b/core/modules/comment/comment.module
index 489a391..10c6387 100644
--- a/core/modules/comment/comment.module
+++ b/core/modules/comment/comment.module
@@ -21,6 +21,8 @@
 use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
 use Drupal\Core\Render\Element;
 use Drupal\Core\Url;
+use Drupal\field\Entity\FieldStorageConfig;
+use Drupal\field\Entity\FieldConfig;
 use Drupal\field\FieldConfigInterface;
 use Drupal\field\FieldStorageConfigInterface;
 use Drupal\node\NodeInterface;
@@ -175,19 +177,6 @@ function comment_field_config_update(FieldConfigInterface $field) {
 }
 
 /**
- * Implements hook_ENTITY_TYPE_insert() for 'field_storage_config'.
- */
-function comment_field_storage_config_insert(FieldStorageConfigInterface $field_storage) {
-  if ($field_storage->getType() == 'comment') {
-    // Check that the target entity type uses an integer ID.
-    $entity_type_id = $field_storage->getTargetEntityTypeId();
-    if (!_comment_entity_uses_integer_id($entity_type_id)) {
-      throw new \UnexpectedValueException('You cannot attach a comment field to an entity with a non-integer ID field');
-    }
-  }
-}
-
-/**
  * Implements hook_ENTITY_TYPE_delete() for 'field_config'.
  */
 function comment_field_config_delete(FieldConfigInterface $field) {
@@ -304,11 +293,6 @@ function comment_form_field_ui_field_storage_add_form_alter(&$form, FormStateInt
   if ($form_state->get('entity_type_id') == 'comment' && $route_match->getParameter('commented_entity_type')) {
     $form['#title'] = \Drupal::service('comment.manager')->getFieldUIPageTitle($route_match->getParameter('commented_entity_type'), $route_match->getParameter('field_name'));
   }
-  if (!_comment_entity_uses_integer_id($form_state->get('entity_type_id'))) {
-    $optgroup = (string) t('General');
-    // You cannot use comment fields on entity types with non-integer IDs.
-    unset($form['add']['new_storage_type']['#options'][$optgroup]['comment']);
-  }
 }
 
 /**
@@ -390,15 +374,9 @@ function comment_entity_insert(EntityInterface $entity) {
  * Implements hook_entity_predelete().
  */
 function comment_entity_predelete(EntityInterface $entity) {
-  // Entities can have non-numeric IDs, but {comment} and
-  // {comment_entity_statistics} tables have integer columns for entity ID, and
-  // PostgreSQL throws exceptions if you attempt query conditions with
-  // mismatched types. So, we need to verify that the ID is numeric (even for an
-  // entity type that has an integer ID, $entity->id() might be a string
-  // containing a number), and then cast it to an integer when querying.
-  if ($entity instanceof FieldableEntityInterface && is_numeric($entity->id())) {
+  if ($entity instanceof FieldableEntityInterface && FieldStorageConfig::loadByName('comment', 'commented_' . $entity->getEntityTypeId())) {
     $entity_query = \Drupal::entityQuery('comment');
-    $entity_query->condition('entity_id', (int) $entity->id());
+    $entity_query->condition('commented_' . $entity->getEntityTypeId() . '.target_id', $entity->id());
     $entity_query->condition('entity_type', $entity->getEntityTypeId());
     $cids = $entity_query->execute();
     entity_delete_multiple('comment', $cids);
@@ -407,27 +385,6 @@ function comment_entity_predelete(EntityInterface $entity) {
 }
 
 /**
- * Determines if an entity type is using an integer-based ID definition.
- *
- * @param string $entity_type_id
- *   The ID the represents the entity type.
- *
- * @return bool
- *   Returns TRUE if the entity type has an integer-based ID definition and
- *   FALSE otherwise.
- */
-function _comment_entity_uses_integer_id($entity_type_id) {
-  $entity_type = \Drupal::entityManager()->getDefinition($entity_type_id);
-  $entity_type_id_key = $entity_type->getKey('id');
-  if ($entity_type_id_key === FALSE) {
-    return FALSE;
-  }
-  $field_definitions = \Drupal::entityManager()->getBaseFieldDefinitions($entity_type->id());
-  $entity_type_id_definition = $field_definitions[$entity_type_id_key];
-  return $entity_type_id_definition->getType() === 'integer';
-}
-
-/**
  * Implements hook_node_update_index().
  */
 function comment_node_update_index(EntityInterface $node) {
diff --git a/core/modules/comment/comment.views.inc b/core/modules/comment/comment.views.inc
index 11abede..c42e739 100644
--- a/core/modules/comment/comment.views.inc
+++ b/core/modules/comment/comment.views.inc
@@ -65,31 +65,6 @@ function comment_views_data_alter(&$data) {
           'entity_id' => $entity_type->getKey('id'),
         ],
       ];
-
-      foreach ($fields as $field_name => $field) {
-        $data[$base_table][$field_name . '_cid'] = [
-          'title' => t('Comments of the @entity_type using field: @field_name', $args + ['@field_name' => $field_name]),
-          'help' => t('Relate all comments on the @entity_type. This will create 1 duplicate record for every comment. Usually if you need this it is better to create a comment view.', $args),
-          'relationship' => [
-            'group' => t('Comment'),
-            'label' => t('Comments'),
-            'base' => 'comment_field_data',
-            'base field' => 'entity_id',
-            'relationship field' => $entity_type->getKey('id'),
-            'id' => 'standard',
-            'extra' => [
-              [
-                'field' => 'entity_type',
-                'value' => $entity_type_id,
-              ],
-              [
-                'field' => 'field_name',
-                'value' => $field_name,
-              ],
-            ],
-          ],
-        ];
-      }
     }
   }
 }
diff --git a/core/modules/comment/config/optional/views.view.comments_recent.yml b/core/modules/comment/config/optional/views.view.comments_recent.yml
index 28613e6..aaa4b07 100644
--- a/core/modules/comment/config/optional/views.view.comments_recent.yml
+++ b/core/modules/comment/config/optional/views.view.comments_recent.yml
@@ -50,10 +50,13 @@ display:
           default_field_elements: true
           hide_empty: false
       relationships:
-        node:
-          field: node
-          id: node
-          table: comment_field_data
+        commented_node:
+          id: commented_node
+          table: comment__commented_node
+          field: commented_node
+          relationship: none
+          group_type: group
+          admin_label: 'commented_node: Content'
           required: true
           plugin_id: standard
       fields:
@@ -180,15 +183,41 @@ display:
           entity_type: comment
           entity_field: status
         status_node:
-          value: '1'
+          id: status_node
           table: node_field_data
           field: status
-          relationship: node
-          id: status_node
-          plugin_id: boolean
+          relationship: commented_node
+          group_type: group
+          admin_label: ''
+          operator: '='
+          value: true
+          group: 1
+          exposed: false
           expose:
+            operator_id: ''
+            label: ''
+            description: ''
+            use_operator: false
             operator: ''
-          group: 1
+            identifier: ''
+            required: false
+            remember: false
+            multiple: false
+            remember_roles:
+              authenticated: authenticated
+          is_grouped: false
+          group_info:
+            label: ''
+            description: ''
+            identifier: ''
+            optional: true
+            widget: select
+            multiple: false
+            remember: false
+            default_group: All
+            default_group_multiple: {  }
+            group_items: {  }
+          plugin_id: boolean
           entity_type: node
           entity_field: status
       sorts:
diff --git a/core/modules/comment/migration_templates/d6_comment.yml b/core/modules/comment/migration_templates/d6_comment.yml
index f4dff98..09927b1 100644
--- a/core/modules/comment/migration_templates/d6_comment.yml
+++ b/core/modules/comment/migration_templates/d6_comment.yml
@@ -14,7 +14,7 @@ process:
     plugin: migration
     migration: d6_comment
     source: pid
-  entity_id: nid
+  'commented_node/target_id': nid
   entity_type: 'constants/entity_type'
   # field_name & comment_type is calculated in
   # \Drupal\migrate_drupal\Plugin\migrate\source\d6\Comment::prepareRow()
diff --git a/core/modules/comment/src/CommentAccessControlHandler.php b/core/modules/comment/src/CommentAccessControlHandler.php
index bcb0fd7..ebd3d3f 100644
--- a/core/modules/comment/src/CommentAccessControlHandler.php
+++ b/core/modules/comment/src/CommentAccessControlHandler.php
@@ -8,6 +8,7 @@
 use Drupal\Core\Field\FieldDefinitionInterface;
 use Drupal\Core\Field\FieldItemListInterface;
 use Drupal\Core\Session\AccountInterface;
+use Drupal\comment\Entity\CommentType;
 
 /**
  * Defines the access control handler for the comment entity type.
@@ -77,6 +78,9 @@ protected function checkFieldAccess($operation, FieldDefinitionInterface $field_
         return AccessResult::allowedIfHasPermission($account, 'administer comments');
       }
 
+      /** @var \Drupal\comment\CommentInterface $entity */
+      $entity = $items->getEntity();
+
       // No user can change read-only fields.
       $read_only_fields = [
         'hostname',
@@ -88,7 +92,7 @@ protected function checkFieldAccess($operation, FieldDefinitionInterface $field_
       $create_only_fields = [
         'comment_type',
         'uuid',
-        'entity_id',
+        CommentType::load($entity->bundle())->getEntityReferenceFieldName(),
         'entity_type',
         'field_name',
         'pid',
@@ -116,8 +120,6 @@ protected function checkFieldAccess($operation, FieldDefinitionInterface $field_
           return AccessResult::forbidden();
         }
         $is_name = $field_definition->getName() === 'name';
-        /** @var \Drupal\comment\CommentInterface $entity */
-        $entity = $items->getEntity();
         $commented_entity = $entity->getCommentedEntity();
         $anonymous_contact = $commented_entity->get($entity->getFieldName())->getFieldDefinition()->getSetting('anonymous');
         $admin_access = AccessResult::allowedIfHasPermission($account, 'administer comments');
diff --git a/core/modules/comment/src/CommentLazyBuilders.php b/core/modules/comment/src/CommentLazyBuilders.php
index 730c840..a51df5e 100644
--- a/core/modules/comment/src/CommentLazyBuilders.php
+++ b/core/modules/comment/src/CommentLazyBuilders.php
@@ -101,7 +101,7 @@ public function __construct(EntityManagerInterface $entity_manager, EntityFormBu
   public function renderForm($commented_entity_type_id, $commented_entity_id, $field_name, $comment_type_id) {
     $values = [
       'entity_type' => $commented_entity_type_id,
-      'entity_id' => $commented_entity_id,
+      'commented_' . $commented_entity_type_id => $commented_entity_id,
       'field_name' => $field_name,
       'comment_type' => $comment_type_id,
       'pid' => NULL,
diff --git a/core/modules/comment/src/CommentManager.php b/core/modules/comment/src/CommentManager.php
index 80cc427..d46ac9c 100644
--- a/core/modules/comment/src/CommentManager.php
+++ b/core/modules/comment/src/CommentManager.php
@@ -3,6 +3,7 @@
 namespace Drupal\comment;
 
 use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
+use Drupal\comment\Entity\CommentType;
 use Drupal\Core\Config\ConfigFactoryInterface;
 use Drupal\Core\Entity\EntityInterface;
 use Drupal\Core\Entity\EntityManagerInterface;
@@ -132,6 +133,67 @@ public function addBodyField($comment_type_id) {
   /**
    * {@inheritdoc}
    */
+  public function addEntityField($comment_type_id) {
+    $comment_type = CommentType::load($comment_type_id);
+    $field_name = $comment_type->getEntityReferenceFieldName();
+    $field_storage = FieldStorageConfig::loadByName('comment', $field_name);
+    if (!$field_storage) {
+      $field_storage = FieldStorageConfig::create([
+        'langcode' => 'en',
+        'status' => TRUE,
+        'dependencies' => [
+          'module' => ['comment', 'entity_reference'],
+        ],
+        'id' => 'comment.' . $field_name,
+        'field_name' => $field_name,
+        'entity_type' => 'comment',
+        'type' => 'entity_reference',
+        'settings' => [
+          'target_type' => $comment_type->getTargetEntityTypeId(),
+          'handler_settings' => [],
+          'handler' => 'default:' . $comment_type->getTargetEntityTypeId(),
+        ],
+        'module' => 'entity_reference',
+        'locked' => TRUE,
+        'cardinality' => 1,
+        'translatable' => FALSE,
+        'indexes' => [],
+        'persist_with_no_fields' => TRUE,
+      ]);
+      $field_storage->save();
+    }
+    if (!FieldConfig::loadByName('comment', $comment_type_id, $field_name)) {
+      $target_entity_type = $this->entityManager->getDefinition($comment_type->getTargetEntityTypeId());
+      $comment_type = CommentType::load($comment_type_id);
+      // Attaches the body field by default.
+      $field = $this->entityManager->getStorage('field_config')->create([
+        'label' => 'Commented ' . $target_entity_type->getLabel(),
+        'bundle' => $comment_type_id,
+        'required' => TRUE,
+        'field_storage' => $field_storage,
+        'settings' => [
+          'target_type' => $comment_type->getTargetEntityTypeId(),
+          'handler_settings' => [],
+          'handler' => 'default:' . $comment_type->getTargetEntityTypeId(),
+        ],
+      ]);
+      $field->save();
+
+      // Assign widget settings for the 'default' form mode.
+      entity_get_form_display('comment', $comment_type_id, 'default')
+        ->removeComponent($field_name)
+        ->save();
+
+      // Assign display settings for the 'default' view mode.
+      entity_get_display('comment', $comment_type_id, 'default')
+        ->removeComponent($field_name)
+        ->save();
+    }
+  }
+
+  /**
+   * {@inheritdoc}
+   */
   public function forbiddenMessage(EntityInterface $entity, $field_name) {
     if (!isset($this->authenticatedCanPostComments)) {
       // We only output a link if we are certain that users will get the
@@ -203,7 +265,7 @@ public function getCountNewComments(EntityInterface $entity, $field_name = NULL,
       // Use the timestamp to retrieve the number of new comments.
       $query = $this->entityManager->getStorage('comment')->getQuery()
         ->condition('entity_type', $entity->getEntityTypeId())
-        ->condition('entity_id', $entity->id())
+        ->condition('commented_' . $entity->getEntityTypeId() . '.target_id', $entity->id())
         ->condition('created', $timestamp, '>')
         ->condition('status', CommentInterface::PUBLISHED);
       if ($field_name) {
diff --git a/core/modules/comment/src/CommentManagerInterface.php b/core/modules/comment/src/CommentManagerInterface.php
index bb286bf..9dbf15b 100644
--- a/core/modules/comment/src/CommentManagerInterface.php
+++ b/core/modules/comment/src/CommentManagerInterface.php
@@ -44,6 +44,14 @@ public function getFields($entity_type_id);
    */
   public function addBodyField($comment_type);
 
+ /**
+   * Creates a commented_entity field.
+   *
+   * @param string $comment_type
+   *   The comment bundle.
+   */
+  public function addEntityField($comment_type);
+
   /**
    * Provides a message if posting comments is forbidden.
    *
diff --git a/core/modules/comment/src/CommentStatistics.php b/core/modules/comment/src/CommentStatistics.php
index 3c6b571..938377b 100644
--- a/core/modules/comment/src/CommentStatistics.php
+++ b/core/modules/comment/src/CommentStatistics.php
@@ -11,6 +11,7 @@
 use Drupal\Core\State\StateInterface;
 use Drupal\Core\Session\AccountInterface;
 use Drupal\user\EntityOwnerInterface;
+use Drupal\field\Entity\FieldStorageConfig;
 
 class CommentStatistics implements CommentStatisticsInterface {
 
@@ -161,7 +162,7 @@ public function getRankingInfo() {
           'alias' => 'ces',
           // Default to comment field as this is the most common use case for
           // nodes.
-          'on' => "ces.entity_id = i.sid AND ces.entity_type = 'node' AND ces.field_name = 'comment'",
+          'on' => "ces.entity_id = CAST(i.sid as CHAR(255)) AND ces.entity_type = 'node' AND ces.field_name = 'comment'",
         ],
         // Inverse law that maps the highest view count on the site to 1 and 0
         // to 0. Note that the ROUND here is necessary for PostgreSQL and SQLite
@@ -184,10 +185,14 @@ public function update(CommentInterface $comment) {
     if (!$this->state->get('comment.maintain_entity_statistics')) {
       return;
     }
-
+    $field_storage = FieldStorageConfig::loadByName('comment', $this->entityManager->getStorage('comment_type')->load($comment->bundle())->getEntityReferenceFieldName());
+    $table_mapping = \Drupal::entityManager()->getStorage('comment')->getTableMapping();
+    $comment_entity_table = $table_mapping->getDedicatedDataTableName($field_storage);
+    $target_id_column = $table_mapping->getFieldColumnName($field_storage, 'target_id');
     $query = $this->database->select('comment_field_data', 'c');
     $query->addExpression('COUNT(cid)');
-    $count = $query->condition('c.entity_id', $comment->getCommentedEntityId())
+    $query->join($comment_entity_table, 'ce', 'c.cid = %alias.entity_id AND %alias.deleted = 0');
+    $count = $query->condition('ce.' . $target_id_column, $comment->getCommentedEntityId())
       ->condition('c.entity_type', $comment->getCommentedEntityTypeId())
       ->condition('c.field_name', $comment->getFieldName())
       ->condition('c.status', CommentInterface::PUBLISHED)
@@ -197,17 +202,17 @@ public function update(CommentInterface $comment) {
 
     if ($count > 0) {
       // Comments exist.
-      $last_reply = $this->database->select('comment_field_data', 'c')
-        ->fields('c', ['cid', 'name', 'changed', 'uid'])
-        ->condition('c.entity_id', $comment->getCommentedEntityId())
+      $last_reply_query = $this->database->select('comment_field_data', 'c');
+      $last_reply_query->join($comment_entity_table, 'ce', 'c.cid = %alias.entity_id AND %alias.deleted = 0');
+      $last_reply_query->fields('c', ['cid', 'name', 'changed', 'uid'])
+        ->condition('ce.' . $target_id_column, $comment->getCommentedEntityId())
         ->condition('c.entity_type', $comment->getCommentedEntityTypeId())
         ->condition('c.field_name', $comment->getFieldName())
         ->condition('c.status', CommentInterface::PUBLISHED)
         ->condition('default_langcode', 1)
         ->orderBy('c.created', 'DESC')
-        ->range(0, 1)
-        ->execute()
-        ->fetchObject();
+        ->range(0, 1);
+      $last_reply = $last_reply_query->execute()->fetchObject();
       // Use merge here because entity could be created before comment field.
       $this->database->merge('comment_entity_statistics')
         ->fields([
diff --git a/core/modules/comment/src/CommentStorage.php b/core/modules/comment/src/CommentStorage.php
index d164d8a..4fcc0d4 100644
--- a/core/modules/comment/src/CommentStorage.php
+++ b/core/modules/comment/src/CommentStorage.php
@@ -12,6 +12,7 @@
 use Drupal\Core\Session\AccountInterface;
 use Drupal\Core\Language\LanguageManagerInterface;
 use Symfony\Component\DependencyInjection\ContainerInterface;
+use Drupal\field\Entity\FieldStorageConfig;
 
 /**
  * Defines the storage handler class for comments.
@@ -67,12 +68,17 @@ public static function createInstance(ContainerInterface $container, EntityTypeI
    * {@inheritdoc}
    */
   public function getMaxThread(CommentInterface $comment) {
-    $query = $this->database->select('comment_field_data', 'c')
-      ->condition('entity_id', $comment->getCommentedEntityId())
-      ->condition('field_name', $comment->getFieldName())
-      ->condition('entity_type', $comment->getCommentedEntityTypeId())
-      ->condition('default_langcode', 1);
-    $query->addExpression('MAX(thread)', 'thread');
+    $field_storage = FieldStorageConfig::loadByName('comment', $this->entityManager->getStorage('comment_type')->load($comment->bundle())->getEntityReferenceFieldName());
+    $table_mapping = \Drupal::entityManager()->getStorage('comment')->getTableMapping();
+    $comment_entity_table = $table_mapping->getDedicatedDataTableName($field_storage);
+    $target_id_column = $table_mapping->getFieldColumnName($field_storage, 'target_id');
+    $query = $this->database->select('comment_field_data', 'c');
+    $query->join($comment_entity_table, 'ce', 'c.cid = %alias.entity_id AND %alias.deleted = 0');
+    $query->condition('ce.' . $target_id_column, $comment->getCommentedEntityId())
+      ->condition('c.field_name', $comment->getFieldName())
+      ->condition('c.entity_type', $comment->getCommentedEntityTypeId())
+      ->condition('c.default_langcode', 1);
+    $query->addExpression('MAX(c.thread)', 'thread');
     return $query->execute()
       ->fetchField();
   }
@@ -81,13 +87,18 @@ public function getMaxThread(CommentInterface $comment) {
    * {@inheritdoc}
    */
   public function getMaxThreadPerThread(CommentInterface $comment) {
-    $query = $this->database->select('comment_field_data', 'c')
-      ->condition('entity_id', $comment->getCommentedEntityId())
-      ->condition('field_name', $comment->getFieldName())
-      ->condition('entity_type', $comment->getCommentedEntityTypeId())
-      ->condition('thread', $comment->getParentComment()->getThread() . '.%', 'LIKE')
-      ->condition('default_langcode', 1);
-    $query->addExpression('MAX(thread)', 'thread');
+    $field_storage = FieldStorageConfig::loadByName('comment', $this->entityManager->getStorage('comment_type')->load($comment->bundle())->getEntityReferenceFieldName());
+    $table_mapping = \Drupal::entityManager()->getStorage('comment')->getTableMapping();
+    $comment_entity_table = $table_mapping->getDedicatedDataTableName($field_storage);
+    $target_id_column = $table_mapping->getFieldColumnName($field_storage, 'target_id');
+    $query = $this->database->select('comment_field_data', 'c');
+    $query->join($comment_entity_table, 'ce', 'c.cid = %alias.entity_id AND %alias.deleted = 0');
+    $query->condition('ce.' . $target_id_column, $comment->getCommentedEntityId())
+      ->condition('c.field_name', $comment->getFieldName())
+      ->condition('c.entity_type', $comment->getCommentedEntityTypeId())
+      ->condition('c.thread', $comment->getParentComment()->getThread() . '.%', 'LIKE')
+      ->condition('c.default_langcode', 1);
+    $query->addExpression('MAX(c.thread)', 'thread');
     return $query->execute()
       ->fetchField();
   }
@@ -98,8 +109,14 @@ public function getMaxThreadPerThread(CommentInterface $comment) {
   public function getDisplayOrdinal(CommentInterface $comment, $comment_mode, $divisor = 1) {
     // Count how many comments (c1) are before $comment (c2) in display order.
     // This is the 0-based display ordinal.
+    $field_storage = FieldStorageConfig::loadByName('comment', $this->entityManager->getStorage('comment_type')->load($comment->bundle())->getEntityReferenceFieldName());
+    $table_mapping = \Drupal::entityManager()->getStorage('comment')->getTableMapping();
+    $comment_entity_table = $table_mapping->getDedicatedDataTableName($field_storage);
+    $target_id_column = $table_mapping->getFieldColumnName($field_storage, 'target_id');
     $query = $this->database->select('comment_field_data', 'c1');
-    $query->innerJoin('comment_field_data', 'c2', 'c2.entity_id = c1.entity_id AND c2.entity_type = c1.entity_type AND c2.field_name = c1.field_name');
+    $query->join($comment_entity_table, 'ce1', 'c1.cid = %alias.entity_id AND %alias.deleted = 0');
+    $query->innerJoin($comment_entity_table, 'ce2', 'ce2.' . $target_id_column . ' = ce1.' . $target_id_column . ' AND ce2.bundle = ce1.bundle');
+    $query->join('comment_field_data', 'c2', '%alias.cid = ce2.entity_id AND ce2.deleted = 0');
     $query->addExpression('COUNT(*)', 'count');
     $query->condition('c2.cid', $comment->id());
     if (!$this->currentUser->hasPermission('administer comments')) {
@@ -146,15 +163,20 @@ public function getNewCommentPageNumber($total_comments, $new_comments, Fieldabl
       // Threaded comments.
 
       // 1. Find all the threads with a new comment.
-      $unread_threads_query = $this->database->select('comment_field_data', 'comment')
-        ->fields('comment', ['thread'])
-        ->condition('entity_id', $entity->id())
-        ->condition('entity_type', $entity->getEntityTypeId())
-        ->condition('field_name', $field_name)
-        ->condition('status', CommentInterface::PUBLISHED)
-        ->condition('default_langcode', 1)
-        ->orderBy('created', 'DESC')
-        ->orderBy('cid', 'DESC')
+      $field_storage = FieldStorageConfig::loadByName('comment', 'commented_' . $entity->getEntityTypeId());
+      $table_mapping = \Drupal::entityManager()->getStorage('comment')->getTableMapping();
+      $comment_entity_table = $table_mapping->getDedicatedDataTableName($field_storage);
+      $target_id_column = $table_mapping->getFieldColumnName($field_storage, 'target_id');
+      $unread_threads_query = $this->database->select('comment_field_data', 'comment');
+      $unread_threads_query->join($comment_entity_table, 'ce', 'comment.cid = %alias.entity_id AND %alias.deleted = 0');
+      $unread_threads_query->fields('comment', ['thread'])
+        ->condition('ce.' . $target_id_column, $entity->id())
+        ->condition('comment.entity_type', $entity->getEntityTypeId())
+        ->condition('comment.field_name', $field_name)
+        ->condition('comment.status', CommentInterface::PUBLISHED)
+        ->condition('comment.default_langcode', 1)
+        ->orderBy('comment.created', 'DESC')
+        ->orderBy('comment.cid', 'DESC')
         ->range(0, $new_comments);
 
       // 2. Find the first thread.
@@ -171,12 +193,15 @@ public function getNewCommentPageNumber($total_comments, $new_comments, Fieldabl
       $first_thread = substr($first_thread, 0, -1);
 
       // Find the number of the first comment of the first unread thread.
-      $count = $this->database->query('SELECT COUNT(*) FROM {comment_field_data} WHERE entity_id = :entity_id
-                        AND entity_type = :entity_type
-                        AND field_name = :field_name
-                        AND status = :status
-                        AND SUBSTRING(thread, 1, (LENGTH(thread) - 1)) < :thread
-                        AND default_langcode = 1', [
+      $count = $this->database->query('SELECT COUNT(*) FROM {comment_field_data} c
+                        INNER JOIN {' . $comment_entity_table . '} ce
+                        ON c.cid = ce.entity_id AND ce.deleted = 0
+                        WHERE ce.' . $target_id_column . ' = :entity_id
+                        AND c.entity_type = :entity_type
+                        AND c.field_name = :field_name
+                        AND c.status = :status
+                        AND SUBSTRING(c.thread, 1, (LENGTH(c.thread) - 1)) < :thread
+                        AND c.default_langcode = 1', [
         ':status' => CommentInterface::PUBLISHED,
         ':entity_id' => $entity->id(),
         ':field_name' => $field_name,
@@ -258,10 +283,15 @@ public function getChildCids(array $comments) {
    * to consider the trailing "/" so we use a substring only.
    */
   public function loadThread(EntityInterface $entity, $field_name, $mode, $comments_per_page = 0, $pager_id = 0) {
+    $field_storage = FieldStorageConfig::loadByName('comment', 'commented_' . $entity->getEntityTypeId());
+    $table_mapping = \Drupal::entityManager()->getStorage('comment')->getTableMapping();
+    $comment_entity_table = $table_mapping->getDedicatedDataTableName($field_storage);
+    $target_id_column = $table_mapping->getFieldColumnName($field_storage, 'target_id');
     $query = $this->database->select('comment_field_data', 'c');
+    $query->join($comment_entity_table, 'ce', 'c.cid = %alias.entity_id AND %alias.deleted = 0');
     $query->addField('c', 'cid');
     $query
-      ->condition('c.entity_id', $entity->id())
+      ->condition('ce.' . $target_id_column, $entity->id())
       ->condition('c.entity_type', $entity->getEntityTypeId())
       ->condition('c.field_name', $field_name)
       ->condition('c.default_langcode', 1)
@@ -279,9 +309,10 @@ public function loadThread(EntityInterface $entity, $field_name, $mode, $comment
       }
 
       $count_query = $this->database->select('comment_field_data', 'c');
+      $count_query->join($comment_entity_table, 'ce', 'c.cid = %alias.entity_id AND %alias.deleted = 0');
       $count_query->addExpression('COUNT(*)');
       $count_query
-        ->condition('c.entity_id', $entity->id())
+        ->condition('ce.' . $target_id_column, $entity->id())
         ->condition('c.entity_type', $entity->getEntityTypeId())
         ->condition('c.field_name', $field_name)
         ->condition('c.default_langcode', 1)
diff --git a/core/modules/comment/src/CommentStorageSchema.php b/core/modules/comment/src/CommentStorageSchema.php
index 2106a8e..e451d7c 100644
--- a/core/modules/comment/src/CommentStorageSchema.php
+++ b/core/modules/comment/src/CommentStorageSchema.php
@@ -5,6 +5,7 @@
 use Drupal\Core\Entity\ContentEntityTypeInterface;
 use Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema;
 use Drupal\Core\Field\FieldStorageDefinitionInterface;
+use Drupal\comment\Entity\CommentType;
 
 /**
  * Defines the comment schema handler.
@@ -20,16 +21,14 @@ protected function getEntitySchema(ContentEntityTypeInterface $entity_type, $res
     $schema['comment_field_data']['indexes'] += [
       'comment__status_pid' => ['pid', 'status'],
       'comment__num_new' => [
-        'entity_id',
         'entity_type',
         'comment_type',
         'status',
         'created',
         'cid',
-        'thread',
+        ['thread', 191],
       ],
       'comment__entity_langcode' => [
-        'entity_id',
         'entity_type',
         'comment_type',
         'default_langcode',
@@ -70,4 +69,54 @@ protected function getSharedTableFieldSchema(FieldStorageDefinitionInterface $st
     return $schema;
   }
 
+  public function onEntityTypeUpdate(\Drupal\Core\Entity\EntityTypeInterface $entity_type, \Drupal\Core\Entity\EntityTypeInterface $original) {
+    $storage_definitions = $this->entityManager->getFieldStorageDefinitions($entity_type->id());
+    $original_storage_definitions = $this->entityManager->getLastInstalledFieldStorageDefinitions($original->id());
+    if (isset($original_storage_definitions['entity_id']) && !isset($storage_definitions['entity_id'])) {
+      // Create a table to temporarily store the data until
+      // comment_update_8302() is executed.
+      db_create_table('comment_update_8302', [
+        'fields' => [
+          'cid' => [
+            'type' => 'int',
+            'not null' => TRUE,
+            'default' => 0,
+            'description' => 'The {comment}.cid.',
+          ],
+          'entity_id' => [
+            'type' => 'int',
+            'not null' => TRUE,
+            'default' => 0,
+            'description' => 'The entity id.',
+          ],
+        ],
+      ]);
+      db_insert('comment_update_8302')->from(
+        db_select('comment_field_data', 'c')->fields('c', ['cid', 'entity_id'])
+      )->execute();
+      db_change_field(
+        'comment_field_data',
+        'entity_id',
+        'entity_id',
+        [
+          'type' => 'int',
+          'not null' => FALSE,
+          'default' => NULL,
+          'description' => 'The entity id.',
+        ]
+      );
+      db_update('comment_field_data')->fields(['entity_id' => NULL])->execute();
+      // Create the reference fields for each comment bundle.
+      $comment_types = CommentType::loadMultiple();
+      foreach ($comment_types as $comment_type) {
+        \Drupal::service('comment.manager')->addEntityField($comment_type->id());
+      }
+
+      // Drop the indexes that use the deleted field.
+      db_drop_index('comment_field_data', 'comment__num_new');
+      db_drop_index('comment_field_data', 'comment__entity_langcode');
+    }
+    parent::onEntityTypeUpdate($entity_type, $original);
+  }
+
 }
diff --git a/core/modules/comment/src/CommentTypeForm.php b/core/modules/comment/src/CommentTypeForm.php
index 9cb147f..33ee588 100644
--- a/core/modules/comment/src/CommentTypeForm.php
+++ b/core/modules/comment/src/CommentTypeForm.php
@@ -163,6 +163,7 @@ public function save(array $form, FormStateInterface $form_state) {
     }
     else {
       $this->commentManager->addBodyField($comment_type->id());
+      $this->commentManager->addEntityField($comment_type->id());
       drupal_set_message(t('Comment type %label has been added.', ['%label' => $comment_type->label()]));
       $this->logger->notice('Comment type %label has been added.', ['%label' => $comment_type->label(), 'link' => $edit_link]);
     }
diff --git a/core/modules/comment/src/CommentTypeInterface.php b/core/modules/comment/src/CommentTypeInterface.php
index acde96c..ce2d6e2 100644
--- a/core/modules/comment/src/CommentTypeInterface.php
+++ b/core/modules/comment/src/CommentTypeInterface.php
@@ -35,4 +35,13 @@ public function setDescription($description);
    */
   public function getTargetEntityTypeId();
 
+  /**
+   * Gets the entity reference field name for this comment type.
+   *
+   * @return string
+   *   The field name of the entity reference field referencing the commented
+   *   entity.
+   */
+  public function getEntityReferenceFieldName();
+
 }
diff --git a/core/modules/comment/src/CommentViewsData.php b/core/modules/comment/src/CommentViewsData.php
index 52af015..db9134a 100644
--- a/core/modules/comment/src/CommentViewsData.php
+++ b/core/modules/comment/src/CommentViewsData.php
@@ -183,33 +183,6 @@ public function getViewsData() {
 
     $entities_types = \Drupal::entityManager()->getDefinitions();
 
-    // Provide a relationship for each entity type except comment.
-    foreach ($entities_types as $type => $entity_type) {
-      if ($type == 'comment' || !$entity_type->entityClassImplements(ContentEntityInterface::class) || !$entity_type->getBaseTable()) {
-        continue;
-      }
-      if ($fields = \Drupal::service('comment.manager')->getFields($type)) {
-        $data['comment_field_data'][$type] = [
-          'relationship' => [
-            'title' => $entity_type->getLabel(),
-            'help' => $this->t('The @entity_type to which the comment is a reply to.', ['@entity_type' => $entity_type->getLabel()]),
-            'base' => $entity_type->getDataTable() ?: $entity_type->getBaseTable(),
-            'base field' => $entity_type->getKey('id'),
-            'relationship field' => 'entity_id',
-            'id' => 'standard',
-            'label' => $entity_type->getLabel(),
-            'extra' => [
-              [
-                'field' => 'entity_type',
-                'value' => $type,
-                'table' => 'comment_field_data'
-              ],
-            ],
-          ],
-        ];
-      }
-    }
-
     $data['comment_field_data']['uid']['title'] = $this->t('Author uid');
     $data['comment_field_data']['uid']['help'] = $this->t('If you need more fields than the uid add the comment: author relationship');
     $data['comment_field_data']['uid']['relationship']['title'] = $this->t('Author');
@@ -239,6 +212,8 @@ public function getViewsData() {
       if (\Drupal::service('comment.manager')->getFields($type)) {
         $data['comment_entity_statistics']['table']['join'][$entity_type->getDataTable() ?: $entity_type->getBaseTable()] = [
           'type' => 'INNER',
+          'join_id' => 'cast',
+          'cast_as' => 'CHAR(255)',
           'left_field' => $entity_type->getKey('id'),
           'field' => 'entity_id',
           'extra' => [
diff --git a/core/modules/comment/src/Controller/CommentController.php b/core/modules/comment/src/Controller/CommentController.php
index c834fa6..6d1a7b7 100644
--- a/core/modules/comment/src/Controller/CommentController.php
+++ b/core/modules/comment/src/Controller/CommentController.php
@@ -241,7 +241,7 @@ public function getReplyForm(Request $request, EntityInterface $entity, $field_n
 
     // Show the actual reply box.
     $comment = $this->entityManager()->getStorage('comment')->create([
-      'entity_id' => $entity->id(),
+      'commented_' . $entity->getEntityTypeId() => $entity->id(),
       'pid' => $pid,
       'entity_type' => $entity->getEntityTypeId(),
       'field_name' => $field_name,
diff --git a/core/modules/comment/src/Entity/Comment.php b/core/modules/comment/src/Entity/Comment.php
index a5f1966..ebd330c 100644
--- a/core/modules/comment/src/Entity/Comment.php
+++ b/core/modules/comment/src/Entity/Comment.php
@@ -242,11 +242,6 @@ public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
       ->setDescription(t('The parent comment ID if this is a reply to a comment.'))
       ->setSetting('target_type', 'comment');
 
-    $fields['entity_id'] = BaseFieldDefinition::create('entity_reference')
-      ->setLabel(t('Entity ID'))
-      ->setDescription(t('The ID of the entity of which this comment is a reply.'))
-      ->setRequired(TRUE);
-
     $fields['subject'] = BaseFieldDefinition::create('string')
       ->setLabel(t('Subject'))
       ->setTranslatable(TRUE)
@@ -324,18 +319,6 @@ public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
   /**
    * {@inheritdoc}
    */
-  public static function bundleFieldDefinitions(EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) {
-    if ($comment_type = CommentType::load($bundle)) {
-      $fields['entity_id'] = clone $base_field_definitions['entity_id'];
-      $fields['entity_id']->setSetting('target_type', $comment_type->getTargetEntityTypeId());
-      return $fields;
-    }
-    return [];
-  }
-
-  /**
-   * {@inheritdoc}
-   */
   public function hasParentComment() {
     return (bool) $this->get('pid')->target_id;
   }
@@ -351,14 +334,14 @@ public function getParentComment() {
    * {@inheritdoc}
    */
   public function getCommentedEntity() {
-    return $this->get('entity_id')->entity;
+    return $this->get(CommentType::load($this->bundle())->getEntityReferenceFieldName())->entity;
   }
 
   /**
    * {@inheritdoc}
    */
   public function getCommentedEntityId() {
-    return $this->get('entity_id')->target_id;
+    return $this->get(CommentType::load($this->bundle())->getEntityReferenceFieldName())->target_id;
   }
 
   /**
diff --git a/core/modules/comment/src/Entity/CommentType.php b/core/modules/comment/src/Entity/CommentType.php
index a773c58..68a0707 100644
--- a/core/modules/comment/src/Entity/CommentType.php
+++ b/core/modules/comment/src/Entity/CommentType.php
@@ -99,4 +99,11 @@ public function getTargetEntityTypeId() {
     return $this->target_entity_type_id;
   }
 
+  /**
+   * {@inheritdoc}
+   */
+  public function getEntityReferenceFieldName() {
+    return 'commented_' . $this->getTargetEntityTypeId();
+  }
+
 }
diff --git a/core/modules/comment/src/Form/DeleteForm.php b/core/modules/comment/src/Form/DeleteForm.php
index fa7ab9d..e5565f8 100644
--- a/core/modules/comment/src/Form/DeleteForm.php
+++ b/core/modules/comment/src/Form/DeleteForm.php
@@ -14,7 +14,7 @@ class DeleteForm extends ContentEntityDeleteForm {
    */
   public function getCancelUrl() {
     // Point to the entity of which this comment is a reply.
-    return $this->entity->get('entity_id')->entity->urlInfo();
+    return $this->entity->getCommentedEntity()->urlInfo();
   }
 
   /**
diff --git a/core/modules/comment/src/Plugin/EntityReferenceSelection/CommentSelection.php b/core/modules/comment/src/Plugin/EntityReferenceSelection/CommentSelection.php
index 2492fc4..bc0f2ad 100644
--- a/core/modules/comment/src/Plugin/EntityReferenceSelection/CommentSelection.php
+++ b/core/modules/comment/src/Plugin/EntityReferenceSelection/CommentSelection.php
@@ -5,6 +5,7 @@
 use Drupal\Core\Database\Query\SelectInterface;
 use Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection;
 use Drupal\comment\CommentInterface;
+use Drupal\field\Entity\FieldStorageConfig;
 
 /**
  * Provides specific access control for the comment entity type.
@@ -68,16 +69,21 @@ public function validateReferenceableNewEntities(array $entities) {
   public function entityQueryAlter(SelectInterface $query) {
     $tables = $query->getTables();
     $data_table = 'comment_field_data';
+    $field_storage = FieldStorageConfig::loadByName('comment', 'commented_node');
+    $table_mapping = \Drupal::entityManager()->getStorage('comment')->getTableMapping();
+    $comment_entity_table = $table_mapping->getDedicatedDataTableName($field_storage);
+    $target_id_column = $table_mapping->getFieldColumnName($field_storage, 'target_id');
     if (!isset($tables['comment_field_data']['alias'])) {
       // If no conditions join against the comment data table, it should be
       // joined manually to allow node access processing.
       $query->innerJoin($data_table, NULL, "base_table.cid = $data_table.cid AND $data_table.default_langcode = 1");
     }
-
+    $query->condition($data_table . '.entity_type', 'node');
+    $query->join($comment_entity_table, 'ce', $data_table . '.cid = %alias.entity_id AND %alias.deleted = 0');
     // The Comment module doesn't implement any proper comment access,
     // and as a consequence doesn't make sure that comments cannot be viewed
     // when the user doesn't have access to the node.
-    $node_alias = $query->innerJoin('node_field_data', 'n', '%alias.nid = ' . $data_table . '.entity_id AND ' . $data_table . ".entity_type = 'node'");
+    $node_alias = $query->innerJoin('node_field_data', 'n', '%alias.nid = ce.' . $target_id_column);
     // Pass the query to the node access control.
     $this->reAlterQuery($query, 'node_access', $node_alias);
 
diff --git a/core/modules/comment/src/Plugin/migrate/destination/EntityCommentType.php b/core/modules/comment/src/Plugin/migrate/destination/EntityCommentType.php
index 9bee87a..8b4564c 100644
--- a/core/modules/comment/src/Plugin/migrate/destination/EntityCommentType.php
+++ b/core/modules/comment/src/Plugin/migrate/destination/EntityCommentType.php
@@ -18,6 +18,7 @@ class EntityCommentType extends EntityConfigBase {
   public function import(Row $row, array $old_destination_id_values = []) {
     $entity_ids = parent::import($row, $old_destination_id_values);
     \Drupal::service('comment.manager')->addBodyField(reset($entity_ids));
+    \Drupal::service('comment.manager')->addEntityField(reset($entity_ids));
     return $entity_ids;
   }
 
diff --git a/core/modules/comment/src/Plugin/views/argument/UserUid.php b/core/modules/comment/src/Plugin/views/argument/UserUid.php
index 7023102..b698a1e 100644
--- a/core/modules/comment/src/Plugin/views/argument/UserUid.php
+++ b/core/modules/comment/src/Plugin/views/argument/UserUid.php
@@ -6,6 +6,7 @@
 use Drupal\Core\Database\Query\Condition;
 use Drupal\views\Plugin\views\argument\ArgumentPluginBase;
 use Symfony\Component\DependencyInjection\ContainerInterface;
+use Drupal\field\Entity\FieldStorageConfig;
 
 /**
  * Argument handler to accept a user id to check for nodes that
@@ -82,13 +83,18 @@ public function query($group_by = FALSE) {
 
     // Use the table definition to correctly add this user ID condition.
     if ($this->table != 'comment_field_data') {
+      $field_storage = FieldStorageConfig::loadByName('comment', 'commented_' . $this->definition['entity_type']);
+      $table_mapping = \Drupal::entityManager()->getStorage('comment')->getTableMapping();
+      $comment_entity_table = $table_mapping->getDedicatedDataTableName($field_storage);
+      $target_id_column = $table_mapping->getFieldColumnName($field_storage, 'target_id');
       $subselect = $this->database->select('comment_field_data', 'c');
+      $subselect->join($comment_entity_table, 'ce', 'c.cid = %alias.entity_id AND %alias.deleted = 0');
       $subselect->addField('c', 'cid');
       $subselect->condition('c.uid', $this->argument);
 
       $entity_id = $this->definition['entity_id'];
       $entity_type = $this->definition['entity_type'];
-      $subselect->where("c.entity_id = $this->tableAlias.$entity_id");
+      $subselect->where("ce.$target_id_column = $this->tableAlias.$entity_id");
       $subselect->condition('c.entity_type', $entity_type);
 
       $condition = (new Condition('OR'))
diff --git a/core/modules/comment/src/Plugin/views/field/NodeNewComments.php b/core/modules/comment/src/Plugin/views/field/NodeNewComments.php
index c53b52e..4c739e9 100644
--- a/core/modules/comment/src/Plugin/views/field/NodeNewComments.php
+++ b/core/modules/comment/src/Plugin/views/field/NodeNewComments.php
@@ -11,6 +11,7 @@
 use Drupal\views\ResultRow;
 use Drupal\views\ViewExecutable;
 use Symfony\Component\DependencyInjection\ContainerInterface;
+use Drupal\field\Entity\FieldStorageConfig;
 
 /**
  * Field handler to display the number of new comments.
@@ -127,7 +128,13 @@ public function preRender(&$values) {
     }
 
     if ($nids) {
-      $result = $this->database->query("SELECT n.nid, COUNT(c.cid) as num_comments FROM {node} n INNER JOIN {comment_field_data} c ON n.nid = c.entity_id AND c.entity_type = 'node' AND c.default_langcode = 1
+      $field_storage = FieldStorageConfig::loadByName('comment', 'commented_node');
+      $table_mapping = \Drupal::entityManager()->getStorage('comment')->getTableMapping();
+      $comment_entity_table = $table_mapping->getDedicatedDataTableName($field_storage);
+      $target_id_column = $table_mapping->getFieldColumnName($field_storage, 'target_id');
+      $result = $this->database->query("SELECT n.nid, COUNT(c.cid) as num_comments FROM {node} n
+        INNER JOIN {" . $comment_entity_table . "} ce ON c.cid = ce.entity_id AND ce.deleted = 0
+        INNER JOIN {comment_field_data} c ON n.nid = c.$target_id_column AND c.entity_type = 'node' AND c.default_langcode = 1
         LEFT JOIN {history} h ON h.nid = n.nid AND h.uid = :h_uid WHERE n.nid IN ( :nids[] )
         AND c.changed > GREATEST(COALESCE(h.timestamp, :timestamp1), :timestamp2) AND c.status = :status GROUP BY n.nid", [
         ':status' => CommentInterface::PUBLISHED,
diff --git a/core/modules/comment/src/Plugin/views/filter/UserUid.php b/core/modules/comment/src/Plugin/views/filter/UserUid.php
index 248b460..e67347e 100644
--- a/core/modules/comment/src/Plugin/views/filter/UserUid.php
+++ b/core/modules/comment/src/Plugin/views/filter/UserUid.php
@@ -4,6 +4,7 @@
 
 use Drupal\Core\Database\Query\Condition;
 use Drupal\views\Plugin\views\filter\FilterPluginBase;
+use Drupal\field\Entity\FieldStorageConfig;
 
 /**
  * Filter handler to accept a user id to check for nodes that user posted or
@@ -18,13 +19,19 @@ class UserUid extends FilterPluginBase {
   public function query() {
     $this->ensureMyTable();
 
+    $field_storage = FieldStorageConfig::loadByName('comment', 'commented_' . $this->definition['entity_type']);
+    $table_mapping = \Drupal::entityManager()->getStorage('comment')->getTableMapping();
+    $comment_entity_table = $table_mapping->getDedicatedDataTableName($field_storage);
+    $target_id_column = $table_mapping->getFieldColumnName($field_storage, 'target_id');
     $subselect = db_select('comment_field_data', 'c');
+    $subselect->join($comment_entity_table, 'ce', 'c.cid = %alias.entity_id AND %alias.deleted = 0');
     $subselect->addField('c', 'cid');
     $subselect->condition('c.uid', $this->value, $this->operator);
 
     $entity_id = $this->definition['entity_id'];
     $entity_type = $this->definition['entity_type'];
     $subselect->where("c.entity_id = $this->tableAlias.$entity_id");
+    $subselect->where("ce.$target_id_column = $this->tableAlias.$entity_id");
     $subselect->condition('c.entity_type', $entity_type);
 
     $condition = (new Condition('OR'))
diff --git a/core/modules/comment/src/Plugin/views/join/Cast.php b/core/modules/comment/src/Plugin/views/join/Cast.php
new file mode 100644
index 0000000..ad8686e
--- /dev/null
+++ b/core/modules/comment/src/Plugin/views/join/Cast.php
@@ -0,0 +1,153 @@
+<?php
+
+/**
+ * @file
+ * Contains Drupal\comment\Plugin\views\join\Cast.
+ */
+
+namespace Drupal\comment\Plugin\views\join;
+
+use Drupal\views\Plugin\views\join\JoinPluginBase;
+
+/**
+ * Join handler for joins that join with a cast expression as the left field.
+ *
+ * For example:
+ * @code
+ * LEFT JOIN my_entity e ON (CAST(base_table.entity_id as CHAR(255)) = e.id
+ * @endcode
+ *
+ * Join definition: same as \Drupal\views\Plugin\views\join\JoinPluginBase,
+ * except:
+ * - cast_as: The type to cast left side of the join clause to.
+ *
+ * @ingroup views_join_handlers
+ * @ViewsJoin("cast")
+ */
+class Cast extends JoinPluginBase {
+  /**
+   * The type to cast left side of the join clause to.
+   *
+   * @var string
+   */
+  public $cast_as;
+
+  /**
+   * {@inheritdoc}
+   */
+  public function __construct(array $configuration, $plugin_id, $plugin_definition) {
+    parent::__construct($configuration, $plugin_id, $plugin_definition);
+    $this->cast_as = $this->configuration['cast_as'];
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function buildJoin($select_query, $table, $view_query) {
+    if (empty($this->configuration['table formula'])) {
+      $right_table = $this->table;
+    }
+    else {
+      $right_table = $this->configuration['table formula'];
+    }
+
+    if ($this->leftTable) {
+      $left = $view_query->getTableInfo($this->leftTable);
+      $left_field = "$left[alias].$this->leftField";
+    }
+    else {
+      // This can be used if left_field is a formula or something. It should be used only *very* rarely.
+      $left_field = $this->leftField;
+    }
+
+    $condition = "CAST($left_field AS $this->cast_as) = $table[alias].$this->field";
+    $arguments = [];
+
+    // Tack on the extra.
+    if (isset($this->extra)) {
+      if (is_array($this->extra)) {
+        $extras = [];
+        foreach ($this->extra as $info) {
+          // Do not require 'value' to be set; allow for field syntax instead.
+          $info += [
+            'value' => NULL,
+          ];
+          // Figure out the table name. Remember, only use aliases provided
+          // if at all possible.
+          $join_table = '';
+          if (!array_key_exists('table', $info)) {
+            $join_table = $table['alias'] . '.';
+          }
+          elseif (isset($info['table'])) {
+            // If we're aware of a table alias for this table, use the table
+            // alias instead of the table name.
+            if (isset($left) && $left['table'] == $info['table']) {
+              $join_table = $left['alias'] . '.';
+            }
+            else {
+              $join_table = $info['table'] . '.';
+            }
+          }
+
+          // Convert a single-valued array of values to the single-value case,
+          // and transform from IN() notation to = notation
+          if (is_array($info['value']) && count($info['value']) == 1) {
+            $info['value'] = array_shift($info['value']);
+          }
+
+          if (is_array($info['value'])) {
+            // With an array of values, we need multiple placeholders and the
+            // 'IN' operator is implicit.
+            $local_arguments = [];
+            foreach ($info['value'] as $value) {
+              $placeholder_i = ':views_join_condition_' . $select_query->nextPlaceholder();
+              $local_arguments[$placeholder_i] = $value;
+            }
+
+            $operator = !empty($info['operator']) ? $info['operator'] : 'IN';
+            $placeholder = '( ' . implode(', ', array_keys($local_arguments)) . ' )';
+            $arguments += $local_arguments;
+          }
+          else {
+            // With a single value, the '=' operator is implicit.
+            $operator = !empty($info['operator']) ? $info['operator'] : '=';
+            $placeholder = ':views_join_condition_' . $select_query->nextPlaceholder();
+          }
+          // Set 'field' as join table field if available or set 'left field' as
+          // join table field is not set.
+          if (isset($info['field'])) {
+            $join_table_field = "$join_table$info[field]";
+            // Allow the value to be set either with the 'value' element or
+            // with 'left_field'.
+            if (isset($info['left_field'])) {
+              $placeholder = "$left[alias].$info[left_field]";
+            }
+            else {
+              $arguments[$placeholder] = $info['value'];
+            }
+          }
+          // Set 'left field' as join table field is not set.
+          else {
+            $join_table_field = "$left[alias].$info[left_field]";
+            $arguments[$placeholder] = $info['value'];
+          }
+          $extras[] = "$join_table_field $operator $placeholder";
+        }
+
+        if ($extras) {
+          if (count($extras) == 1) {
+            $condition .= ' AND ' . array_shift($extras);
+          }
+          else {
+            $condition .= ' AND (' . implode(' ' . $this->extraOperator . ' ', $extras) . ')';
+          }
+        }
+      }
+      elseif ($this->extra && is_string($this->extra)) {
+        $condition .= " AND ($this->extra)";
+      }
+    }
+
+    $select_query->addJoin($this->type, $right_table, $table['alias'], $condition, $arguments);
+  }
+}
diff --git a/core/modules/comment/src/Plugin/views/wizard/Comment.php b/core/modules/comment/src/Plugin/views/wizard/Comment.php
index 61d92c5..5ce522d 100644
--- a/core/modules/comment/src/Plugin/views/wizard/Comment.php
+++ b/core/modules/comment/src/Plugin/views/wizard/Comment.php
@@ -41,7 +41,7 @@ class Comment extends WizardPluginBase {
       'table' => 'node_field_data',
       'field' => 'status',
       'plugin_id' => 'boolean',
-      'relationship' => 'node',
+      'relationship' => 'commented_node',
       'entity_type' => 'node',
       'entity_field' => 'status',
     ],
@@ -68,12 +68,11 @@ protected function defaultDisplayOptions() {
     $display_options['access']['options']['perm'] = 'access comments';
 
     // Add a relationship to nodes.
-    $display_options['relationships']['node']['id'] = 'node';
-    $display_options['relationships']['node']['table'] = 'comment_field_data';
-    $display_options['relationships']['node']['field'] = 'node';
-    $display_options['relationships']['node']['entity_type'] = 'comment_field_data';
-    $display_options['relationships']['node']['required'] = 1;
-    $display_options['relationships']['node']['plugin_id'] = 'standard';
+    $display_options['relationships']['commented_node']['id'] = 'commented_node';
+    $display_options['relationships']['commented_node']['table'] = 'comment__commented_node';
+    $display_options['relationships']['commented_node']['field'] = 'commented_node';
+    $display_options['relationships']['commented_node']['required'] = 1;
+    $display_options['relationships']['commented_node']['plugin_id'] = 'standard';
 
     // Remove the default fields, since we are customizing them here.
     unset($display_options['fields']);
diff --git a/core/modules/comment/src/Tests/CommentAdminTest.php b/core/modules/comment/src/Tests/CommentAdminTest.php
index 980ad30..da1e6ea 100644
--- a/core/modules/comment/src/Tests/CommentAdminTest.php
+++ b/core/modules/comment/src/Tests/CommentAdminTest.php
@@ -50,7 +50,7 @@ public function testApprovalAdminInterface() {
       'cid' => $anonymous_comment4,
       'subject' => $subject,
       'comment_body' => $body,
-      'entity_id' => $this->node->id(),
+      'commented_node' => $this->node->id(),
       'entity_type' => 'node',
       'field_name' => 'comment'
     ]);
@@ -127,7 +127,7 @@ public function testApprovalNodeInterface() {
       'cid' => $anonymous_comment4,
       'subject' => $subject,
       'comment_body' => $body,
-      'entity_id' => $this->node->id(),
+      'commented_node' => $this->node->id(),
       'entity_type' => 'node',
       'field_name' => 'comment'
     ]);
diff --git a/core/modules/comment/src/Tests/CommentBookTest.php b/core/modules/comment/src/Tests/CommentBookTest.php
index 4afd07e..24a8bc3 100644
--- a/core/modules/comment/src/Tests/CommentBookTest.php
+++ b/core/modules/comment/src/Tests/CommentBookTest.php
@@ -47,7 +47,7 @@ public function testBookCommentPrint() {
     $comment = Comment::create([
       'subject' => $comment_subject,
       'comment_body' => $comment_body,
-      'entity_id' => $book_node->id(),
+      'commented_node' => $book_node->id(),
       'entity_type' => 'node',
       'field_name' => 'comment',
       'status' => CommentInterface::PUBLISHED,
diff --git a/core/modules/comment/src/Tests/CommentCSSTest.php b/core/modules/comment/src/Tests/CommentCSSTest.php
index b50e952..a84fb40 100644
--- a/core/modules/comment/src/Tests/CommentCSSTest.php
+++ b/core/modules/comment/src/Tests/CommentCSSTest.php
@@ -44,7 +44,7 @@ public function testCommentClasses() {
       // Add a comment.
       /** @var \Drupal\comment\CommentInterface $comment */
       $comment = Comment::create([
-        'entity_id' => $node->id(),
+        'commented_node' => $node->id(),
         'entity_type' => 'node',
         'field_name' => 'comment',
         'uid' => $case['comment_uid'],
diff --git a/core/modules/comment/src/Tests/CommentCacheTagsTest.php b/core/modules/comment/src/Tests/CommentCacheTagsTest.php
index 12e0ef8..230899f 100644
--- a/core/modules/comment/src/Tests/CommentCacheTagsTest.php
+++ b/core/modules/comment/src/Tests/CommentCacheTagsTest.php
@@ -79,7 +79,7 @@ protected function createEntity() {
         'value' => 'The name "llama" was adopted by European settlers from native Peruvians.',
         'format' => 'plain_text',
       ],
-      'entity_id' => $this->entityTestCamelid->id(),
+      'commented_entity_test' => $entity_test->id(),
       'entity_type' => 'entity_test',
       'field_name' => 'comment',
       'status' => CommentInterface::PUBLISHED,
diff --git a/core/modules/comment/src/Tests/CommentLanguageTest.php b/core/modules/comment/src/Tests/CommentLanguageTest.php
index eee0862..56bd7ad 100644
--- a/core/modules/comment/src/Tests/CommentLanguageTest.php
+++ b/core/modules/comment/src/Tests/CommentLanguageTest.php
@@ -110,7 +110,7 @@ public function testCommentLanguage() {
 
         // Check that comment language matches the current content language.
         $cids = \Drupal::entityQuery('comment')
-          ->condition('entity_id', $node->id())
+          ->condition('commented_node.target_id', $node->id())
           ->condition('entity_type', 'node')
           ->condition('field_name', 'comment')
           ->sort('cid', 'DESC')
diff --git a/core/modules/comment/src/Tests/CommentLinksTest.php b/core/modules/comment/src/Tests/CommentLinksTest.php
index 589a355..1aca360 100644
--- a/core/modules/comment/src/Tests/CommentLinksTest.php
+++ b/core/modules/comment/src/Tests/CommentLinksTest.php
@@ -57,7 +57,7 @@ public function testCommentLinks() {
     // $this->postComment() relies on actual user permissions.
     $comment = Comment::create([
       'cid' => NULL,
-      'entity_id' => $this->node->id(),
+      'commented_node' => $this->node->id(),
       'entity_type' => 'node',
       'field_name' => 'comment',
       'pid' => 0,
diff --git a/core/modules/comment/src/Tests/CommentNewIndicatorTest.php b/core/modules/comment/src/Tests/CommentNewIndicatorTest.php
index 55609e3..16278aa 100644
--- a/core/modules/comment/src/Tests/CommentNewIndicatorTest.php
+++ b/core/modules/comment/src/Tests/CommentNewIndicatorTest.php
@@ -83,7 +83,7 @@ public function testCommentNewCommentsIndicator() {
     /** @var \Drupal\comment\CommentInterface $comment */
     $comment = Comment::create([
       'cid' => NULL,
-      'entity_id' => $this->node->id(),
+      'commented_node' => $this->node->id(),
       'entity_type' => 'node',
       'field_name' => 'comment',
       'pid' => 0,
diff --git a/core/modules/comment/src/Tests/CommentNonNodeTest.php b/core/modules/comment/src/Tests/CommentNonNodeTest.php
index 3c285d8..c7dc4b5 100644
--- a/core/modules/comment/src/Tests/CommentNonNodeTest.php
+++ b/core/modules/comment/src/Tests/CommentNonNodeTest.php
@@ -411,6 +411,7 @@ public function testCommentFunctionality() {
       'target_entity_type_id' => 'entity_test',
     ]);
     $bundle->save();
+    \Drupal::service('comment.manager')->addEntityField('foobar');
 
     // Add a new comment field.
     $storage_edit = [
@@ -473,8 +474,8 @@ public function testsNonIntegerIdEntities() {
     $this->drupalLogin($limited_user);
     // Visit the Field UI field add page.
     $this->drupalGet('entity_test_string_id/structure/entity_test/fields/add-field');
-    // Ensure field isn't shown for string IDs.
-    $this->assertNoOption('edit-new-storage-type', 'comment');
+    // Ensure field is shown for string IDs.
+    $this->assertOption('edit-new-storage-type', 'comment');
     // Ensure a core field type shown.
     $this->assertOption('edit-new-storage-type', 'boolean');
 
@@ -485,8 +486,8 @@ public function testsNonIntegerIdEntities() {
     ]));
     // Visit the Field UI field add page.
     $this->drupalGet('entity_test_no_id/structure/entity_test/fields/add-field');
-    // Ensure field isn't shown for empty IDs.
-    $this->assertNoOption('edit-new-storage-type', 'comment');
+    // Ensure field is shown for empty IDs.
+    $this->assertOption('edit-new-storage-type', 'comment');
     // Ensure a core field type shown.
     $this->assertOption('edit-new-storage-type', 'boolean');
   }
diff --git a/core/modules/comment/src/Tests/CommentTestTrait.php b/core/modules/comment/src/Tests/CommentTestTrait.php
index 038a3df..384ffcb 100644
--- a/core/modules/comment/src/Tests/CommentTestTrait.php
+++ b/core/modules/comment/src/Tests/CommentTestTrait.php
@@ -52,6 +52,8 @@ public function addDefaultCommentField($entity_type, $bundle, $field_name = 'com
     }
     // Add a body field to the comment type.
     \Drupal::service('comment.manager')->addBodyField($comment_type_id);
+    // Add an entity field to the comment type.
+    \Drupal::service('comment.manager')->addEntityField($comment_type_id);
 
     // Add a comment field to the host entity type. Create the field storage if
     // needed.
diff --git a/core/modules/comment/src/Tests/CommentTranslationUITest.php b/core/modules/comment/src/Tests/CommentTranslationUITest.php
index 4613d66..1137de3 100644
--- a/core/modules/comment/src/Tests/CommentTranslationUITest.php
+++ b/core/modules/comment/src/Tests/CommentTranslationUITest.php
@@ -101,7 +101,7 @@ protected function createEntity($values, $langcode, $comment_type = 'comment_art
         ['status' => CommentItemInterface::OPEN]
       ],
     ]);
-    $values['entity_id'] = $node->id();
+    $values['commented_node'] = $node->id();
     $values['entity_type'] = 'node';
     $values['field_name'] = $field_name;
     $values['uid'] = $node->getOwnerId();
diff --git a/core/modules/comment/src/Tests/CommentTypeTest.php b/core/modules/comment/src/Tests/CommentTypeTest.php
index 343bb91..55a9c48 100644
--- a/core/modules/comment/src/Tests/CommentTypeTest.php
+++ b/core/modules/comment/src/Tests/CommentTypeTest.php
@@ -142,7 +142,7 @@ public function testCommentTypeDeletion() {
       'comment_type' => 'foo',
       'entity_type' => 'node',
       'field_name' => 'foo',
-      'entity_id' => $node->id(),
+      'commented_node' => $node->id(),
     ]);
     $comment->save();
 
diff --git a/core/modules/comment/src/Tests/Views/ArgumentUserUIDTest.php b/core/modules/comment/src/Tests/Views/ArgumentUserUIDTest.php
index d3526dc..69c0c2d 100644
--- a/core/modules/comment/src/Tests/Views/ArgumentUserUIDTest.php
+++ b/core/modules/comment/src/Tests/Views/ArgumentUserUIDTest.php
@@ -27,7 +27,7 @@ public function testCommentUserUIDTest() {
 
     $comment = Comment::create([
       'uid' => $new_user->uid->value,
-      'entity_id' => $this->nodeUserCommented->id(),
+      'commented_node' => $this->nodeUserCommented->id(),
       'entity_type' => 'node',
       'field_name' => 'comment',
       'subject' => 'if a woodchuck could chuck wood.',
diff --git a/core/modules/comment/src/Tests/Views/CommentFieldFilterTest.php b/core/modules/comment/src/Tests/Views/CommentFieldFilterTest.php
index 48f7d6d..f653efa 100644
--- a/core/modules/comment/src/Tests/Views/CommentFieldFilterTest.php
+++ b/core/modules/comment/src/Tests/Views/CommentFieldFilterTest.php
@@ -50,8 +50,9 @@ public function setUp() {
     // as it predates the language set-up.
     $comment = [
       'uid' => $this->loggedInUser->id(),
-      'entity_id' => $this->nodeUserCommented->id(),
+      'commented_node' => $this->nodeUserCommented->id(),
       'entity_type' => 'node',
+      'comment_type' => 'comment',
       'field_name' => 'comment',
       'cid' => '',
       'pid' => '',
diff --git a/core/modules/comment/src/Tests/Views/CommentFieldNameTest.php b/core/modules/comment/src/Tests/Views/CommentFieldNameTest.php
index 870a4f4..ee00d56 100644
--- a/core/modules/comment/src/Tests/Views/CommentFieldNameTest.php
+++ b/core/modules/comment/src/Tests/Views/CommentFieldNameTest.php
@@ -43,7 +43,7 @@ protected function setUp() {
     parent::setUp();
     $this->addDefaultCommentField('node', 'page', $this->fieldName);
     $this->customComment = Comment::create([
-      'entity_id' => $this->nodeUserCommented->id(),
+      'commented_node' => $this->nodeUserCommented->id(),
       'entity_type' => 'node',
       'field_name' => $this->fieldName,
     ]);
diff --git a/core/modules/comment/src/Tests/Views/CommentRestExportTest.php b/core/modules/comment/src/Tests/Views/CommentRestExportTest.php
index ed7ce55..8be8108 100644
--- a/core/modules/comment/src/Tests/Views/CommentRestExportTest.php
+++ b/core/modules/comment/src/Tests/Views/CommentRestExportTest.php
@@ -29,7 +29,7 @@ protected function setUp() {
     // Add another anonymous comment.
     $comment = [
       'uid' => 0,
-      'entity_id' => $this->nodeUserCommented->id(),
+      'commented_node' => $this->nodeUserCommented->id(),
       'entity_type' => 'node',
       'field_name' => 'comment',
       'subject' => 'A lot, apparently',
diff --git a/core/modules/comment/src/Tests/Views/CommentTestBase.php b/core/modules/comment/src/Tests/Views/CommentTestBase.php
index d7bec04..5fc9c3c 100644
--- a/core/modules/comment/src/Tests/Views/CommentTestBase.php
+++ b/core/modules/comment/src/Tests/Views/CommentTestBase.php
@@ -19,7 +19,7 @@
    *
    * @var array
    */
-  public static $modules = ['node', 'comment', 'comment_test_views'];
+  public static $modules = ['node', 'comment', 'comment_test_views', 'entity_reference'];
 
   /**
    * A normal user with permission to post comments (without approval).
@@ -75,7 +75,7 @@ protected function setUp() {
 
     $comment = [
       'uid' => $this->loggedInUser->id(),
-      'entity_id' => $this->nodeUserCommented->id(),
+      'commented_node' => $this->nodeUserCommented->id(),
       'entity_type' => 'node',
       'field_name' => 'comment',
       'subject' => 'How much wood would a woodchuck chuck',
diff --git a/core/modules/comment/src/Tests/Views/DefaultViewRecentCommentsTest.php b/core/modules/comment/src/Tests/Views/DefaultViewRecentCommentsTest.php
index 3e5f26b..2e3b223 100644
--- a/core/modules/comment/src/Tests/Views/DefaultViewRecentCommentsTest.php
+++ b/core/modules/comment/src/Tests/Views/DefaultViewRecentCommentsTest.php
@@ -83,7 +83,7 @@ protected function setUp() {
         'status' => CommentInterface::PUBLISHED,
         'field_name' => 'comment',
         'entity_type' => 'node',
-        'entity_id' => $this->node->id(),
+        'commented_node' => $this->node->id(),
       ]);
       $comment->setOwnerId(0);
       $comment->setSubject('Test comment ' . $i);
diff --git a/core/modules/comment/src/Tests/Views/FilterUserUIDTest.php b/core/modules/comment/src/Tests/Views/FilterUserUIDTest.php
index 442a0e7..1d3d366 100644
--- a/core/modules/comment/src/Tests/Views/FilterUserUIDTest.php
+++ b/core/modules/comment/src/Tests/Views/FilterUserUIDTest.php
@@ -33,7 +33,7 @@ public function testCommentUserUIDTest() {
 
     $comment = Comment::create([
       'uid' => $new_user->uid->value,
-      'entity_id' => $this->nodeUserCommented->id(),
+      'commented_node' => $this->nodeUserCommented->id(),
       'entity_type' => 'node',
       'field_name' => 'comment',
       'subject' => 'if a woodchuck could chuck wood.',
diff --git a/core/modules/comment/tests/modules/comment_test_views/test_views/views.view.test_comment_rest.yml b/core/modules/comment/tests/modules/comment_test_views/test_views/views.view.test_comment_rest.yml
index fabd46c..d44fc3f 100644
--- a/core/modules/comment/tests/modules/comment_test_views/test_views/views.view.test_comment_rest.yml
+++ b/core/modules/comment/tests/modules/comment_test_views/test_views/views.view.test_comment_rest.yml
@@ -80,15 +80,15 @@ display:
           hide_empty: false
           default_field_elements: true
       relationships:
-        node:
-          id: node
-          table: comment_field_data
-          field: node
-          required: true
-          plugin_id: standard
+        commented_node:
+          id: commented_node
+          table: comment__commented_node
+          field: commented_node
           relationship: none
           group_type: group
-          admin_label: Content
+          admin_label: 'commented_node: Content'
+          required: true
+          plugin_id: standard
       fields:
         subject:
           id: subject
@@ -340,7 +340,7 @@ display:
           id: nid
           table: node_field_data
           field: nid
-          relationship: node
+          relationship: commented_node
           group_type: group
           admin_label: ''
           default_action: default
diff --git a/core/modules/comment/tests/modules/comment_test_views/test_views/views.view.test_comment_row.yml b/core/modules/comment/tests/modules/comment_test_views/test_views/views.view.test_comment_row.yml
index 0b36ef8..196f9ba 100644
--- a/core/modules/comment/tests/modules/comment_test_views/test_views/views.view.test_comment_row.yml
+++ b/core/modules/comment/tests/modules/comment_test_views/test_views/views.view.test_comment_row.yml
@@ -73,14 +73,15 @@ display:
         options:
           view_mode: full
       relationships:
-        node:
-          field: node
-          id: node
-          required: true
-          table: comment_field_data
+        commented_node:
+          id: commented_node
+          table: comment__commented_node
+          field: commented_node
           relationship: none
           group_type: group
-          admin_label: Content
+          admin_label: 'commented_node: Content'
+          required: true
+          plugin_id: standard
       fields:
         subject:
           id: subject
@@ -131,14 +132,40 @@ display:
           entity_type: comment
           entity_field: status
         status_node:
-          value: '1'
+          id: status_node
           table: node_field_data
           field: status
-          relationship: node
-          id: status_node
+          relationship: commented_node
+          group_type: group
+          admin_label: ''
+          operator: '='
+          value: true
+          group: 1
+          exposed: false
           expose:
+            operator_id: ''
+            label: ''
+            description: ''
+            use_operator: false
             operator: ''
-          group: 1
+            identifier: ''
+            required: false
+            remember: false
+            multiple: false
+            remember_roles:
+              authenticated: authenticated
+          is_grouped: false
+          group_info:
+            label: ''
+            description: ''
+            identifier: ''
+            optional: true
+            widget: select
+            multiple: false
+            remember: false
+            default_group: All
+            default_group_multiple: {  }
+            group_items: {  }
           plugin_id: boolean
           entity_type: node
           entity_field: status
diff --git a/core/modules/comment/tests/modules/comment_test_views/test_views/views.view.test_comment_rss.yml b/core/modules/comment/tests/modules/comment_test_views/test_views/views.view.test_comment_rss.yml
index 69dc586..218ae60 100644
--- a/core/modules/comment/tests/modules/comment_test_views/test_views/views.view.test_comment_rss.yml
+++ b/core/modules/comment/tests/modules/comment_test_views/test_views/views.view.test_comment_rss.yml
@@ -35,11 +35,15 @@ display:
       row:
         type: fields
       relationships:
-        node:
-          field: node
-          id: node
+        commented_node:
+          id: commented_node
+          table: comment__commented_node
+          field: commented_node
+          relationship: none
+          group_type: group
+          admin_label: 'commented_node: Content'
           required: true
-          table: comment_field_data
+          plugin_id: standard
       fields:
         subject:
           id: subject
diff --git a/core/modules/comment/tests/modules/comment_test_views/test_views/views.view.test_field_filters.yml b/core/modules/comment/tests/modules/comment_test_views/test_views/views.view.test_field_filters.yml
index 76c67c6..c318345 100644
--- a/core/modules/comment/tests/modules/comment_test_views/test_views/views.view.test_field_filters.yml
+++ b/core/modules/comment/tests/modules/comment_test_views/test_views/views.view.test_field_filters.yml
@@ -56,16 +56,7 @@ display:
         type: 'entity:comment'
         options:
           view_mode: default
-      relationships:
-        node:
-          id: node
-          table: comment_field_data
-          field: node
-          required: true
-          plugin_id: standard
-          relationship: none
-          group_type: group
-          admin_label: Content
+      relationships: {  }
       fields:
         subject:
           id: subject
diff --git a/core/modules/comment/tests/src/Kernel/CommentDefaultFormatterCacheTagsTest.php b/core/modules/comment/tests/src/Kernel/CommentDefaultFormatterCacheTagsTest.php
index bdea71d..ec4cef0 100644
--- a/core/modules/comment/tests/src/Kernel/CommentDefaultFormatterCacheTagsTest.php
+++ b/core/modules/comment/tests/src/Kernel/CommentDefaultFormatterCacheTagsTest.php
@@ -100,7 +100,7 @@ public function testCacheTags() {
         'value' => 'Llamas are cool!',
         'format' => 'plain_text',
       ],
-      'entity_id' => $commented_entity->id(),
+      'commented_entity_test' => $commented_entity->id(),
       'entity_type' => 'entity_test',
       'field_name' => 'comment',
       'comment_type' => 'comment',
diff --git a/core/modules/comment/tests/src/Kernel/CommentFieldAccessTest.php b/core/modules/comment/tests/src/Kernel/CommentFieldAccessTest.php
index 5046353..f15a9b0 100644
--- a/core/modules/comment/tests/src/Kernel/CommentFieldAccessTest.php
+++ b/core/modules/comment/tests/src/Kernel/CommentFieldAccessTest.php
@@ -63,7 +63,7 @@ class CommentFieldAccessTest extends EntityKernelTestBase {
     'uuid',
     'pid',
     'comment_type',
-    'entity_id',
+    'commented_entity_test',
     'entity_type',
     'field_name',
   ];
@@ -151,7 +151,7 @@ public function testAccessToAdministrativeFields() {
       'hostname' => 'magic.example.com',
       'mail' => 'tonythemagicalpony@example.com',
       'subject' => 'Bruce the Mesopotamian moose',
-      'entity_id' => $host->id(),
+      'commented_entity_test' => $host->id(),
       'comment_type' => 'comment',
       'field_name' => 'comment',
       'pid' => 0,
@@ -163,7 +163,7 @@ public function testAccessToAdministrativeFields() {
       'entity_type' => 'entity_test',
       'hostname' => 'magic.example.com',
       'subject' => 'Brian the messed up lion',
-      'entity_id' => $host->id(),
+      'commented_entity_test' => $host->id(),
       'comment_type' => 'comment',
       'field_name' => 'comment',
       'status' => 1,
@@ -177,7 +177,7 @@ public function testAccessToAdministrativeFields() {
       // Unpublished.
       'status' => 0,
       'subject' => 'Gail the minky whale',
-      'entity_id' => $host->id(),
+      'commented_entity_test' => $host->id(),
       'comment_type' => 'comment',
       'field_name' => 'comment_other',
       'pid' => $comment2->id(),
@@ -191,7 +191,7 @@ public function testAccessToAdministrativeFields() {
       // Unpublished.
       'status' => 0,
       'subject' => 'Daniel the Cocker-Spaniel',
-      'entity_id' => $host->id(),
+      'commented_entity_test' => $host->id(),
       'comment_type' => 'comment',
       'field_name' => 'comment_other',
       'pid' => 0,
diff --git a/core/modules/comment/tests/src/Kernel/CommentStringIdEntitiesTest.php b/core/modules/comment/tests/src/Kernel/CommentStringIdEntitiesTest.php
index adbe1b0..a2f6d30 100644
--- a/core/modules/comment/tests/src/Kernel/CommentStringIdEntitiesTest.php
+++ b/core/modules/comment/tests/src/Kernel/CommentStringIdEntitiesTest.php
@@ -56,10 +56,10 @@ public function testCommentFieldNonStringId() {
         'type' => 'comment',
       ]);
       $field_storage->save();
-      $this->fail('Did not throw an exception as expected.');
+      $this->pass('No exception thrown when trying to create comment field on Entity Type with string ID.');
     }
     catch (\UnexpectedValueException $e) {
-      $this->pass('Exception thrown when trying to create comment field on Entity Type with string ID.');
+      $this->fail('Exception thrown when trying to create comment field on Entity Type with string ID.');
     }
   }
 
diff --git a/core/modules/comment/tests/src/Kernel/CommentValidationTest.php b/core/modules/comment/tests/src/Kernel/CommentValidationTest.php
index 98b7715..9177bd5 100644
--- a/core/modules/comment/tests/src/Kernel/CommentValidationTest.php
+++ b/core/modules/comment/tests/src/Kernel/CommentValidationTest.php
@@ -43,6 +43,7 @@ public function testValidation() {
       'label' => 'comment',
       'target_entity_type_id' => 'node',
     ])->save();
+    \Drupal::service('comment.manager')->addEntityField('comment');
 
     // Add comment field to content.
     $this->entityManager->getStorage('field_storage_config')->create([
@@ -77,7 +78,7 @@ public function testValidation() {
     $node->save();
 
     $comment = $this->entityManager->getStorage('comment')->create([
-      'entity_id' => $node->id(),
+      'commented_node' => $node->id(),
       'entity_type' => 'node',
       'field_name' => 'comment',
       'comment_body' => $this->randomMachineName(),
@@ -142,7 +143,7 @@ public function testValidation() {
     $node = Node::load($node->id());
     // Create a new comment with the new field.
     $comment = $this->entityManager->getStorage('comment')->create([
-      'entity_id' => $node->id(),
+      'commented_node' => $node->id(),
       'entity_type' => 'node',
       'field_name' => 'comment',
       'comment_body' => $this->randomMachineName(),
@@ -156,7 +157,7 @@ public function testValidation() {
 
     // Test creating a default comment with a given user id works.
     $comment = $this->entityManager->getStorage('comment')->create([
-      'entity_id' => $node->id(),
+      'commented_node' => $node->id(),
       'entity_type' => 'node',
       'field_name' => 'comment',
       'comment_body' => $this->randomMachineName(),
@@ -167,7 +168,7 @@ public function testValidation() {
 
     // Test specifying a wrong author name does not work.
     $comment = $this->entityManager->getStorage('comment')->create([
-      'entity_id' => $node->id(),
+      'commented_node' => $node->id(),
       'entity_type' => 'node',
       'field_name' => 'comment',
       'comment_body' => $this->randomMachineName(),
diff --git a/core/modules/comment/tests/src/Kernel/Views/CommentUserNameTest.php b/core/modules/comment/tests/src/Kernel/Views/CommentUserNameTest.php
index cad7b2b..6e0a8db 100644
--- a/core/modules/comment/tests/src/Kernel/Views/CommentUserNameTest.php
+++ b/core/modules/comment/tests/src/Kernel/Views/CommentUserNameTest.php
@@ -3,6 +3,7 @@
 namespace Drupal\Tests\comment\Kernel\Views;
 
 use Drupal\comment\Entity\Comment;
+use Drupal\comment\Entity\CommentType;
 use Drupal\Core\Session\AnonymousUserSession;
 use Drupal\Tests\views\Kernel\ViewsKernelTestBase;
 use Drupal\user\Entity\Role;
@@ -26,7 +27,7 @@ class CommentUserNameTest extends ViewsKernelTestBase {
   /**
    * {@inheritdoc}
    */
-  public static $modules = ['user', 'comment', 'entity_test'];
+  public static $modules = ['user', 'comment', 'entity_test', 'field', 'entity_reference'];
 
   /**
    * {@inheritdoc}
@@ -67,6 +68,15 @@ protected function setUp($import_test_views = TRUE) {
     ]);
     $this->adminUser->save();
 
+    $comment_type = CommentType::create([
+      'id' => 'entity_test',
+      'label' => 'Entity test comments',
+      'description' => 'Entity test comment field',
+      'target_entity_type_id' => 'entity_test',
+    ]);
+    $comment_type->save();
+    \Drupal::service('comment.manager')->addEntityField('entity_test');
+
     // Create some comments.
     $comment = Comment::create([
       'subject' => 'My comment title',
diff --git a/core/modules/comment/tests/src/Kernel/Views/CommentViewsFieldAccessTest.php b/core/modules/comment/tests/src/Kernel/Views/CommentViewsFieldAccessTest.php
index f807c58..0c2815b 100644
--- a/core/modules/comment/tests/src/Kernel/Views/CommentViewsFieldAccessTest.php
+++ b/core/modules/comment/tests/src/Kernel/Views/CommentViewsFieldAccessTest.php
@@ -3,6 +3,7 @@
 namespace Drupal\Tests\comment\Kernel\Views;
 
 use Drupal\comment\Entity\Comment;
+use Drupal\comment\Entity\CommentType;
 use Drupal\user\Entity\User;
 use Drupal\Tests\views\Kernel\Handler\FieldFieldAccessTestBase;
 
@@ -16,7 +17,7 @@ class CommentViewsFieldAccessTest extends FieldFieldAccessTestBase {
   /**
    * {@inheritdoc}
    */
-  public static $modules = ['comment', 'entity_test'];
+  public static $modules = ['comment', 'entity_test', 'field', 'entity_reference'];
 
   /**
    * {@inheritdoc}
@@ -36,6 +37,15 @@ public function testCommentFields() {
     ]);
     $user->save();
 
+    $comment_type = CommentType::create([
+      'id' => 'entity_test',
+      'label' => 'Entity test comments',
+      'description' => 'Entity test comment field',
+      'target_entity_type_id' => 'entity_test',
+    ]);
+    $comment_type->save();
+    \Drupal::service('comment.manager')->addEntityField('entity_test');
+
     $comment = Comment::create([
       'subject' => 'My comment title',
       'uid' => $user->id(),
diff --git a/core/modules/forum/config/optional/field.field.comment.comment_forum.commented_node.yml b/core/modules/forum/config/optional/field.field.comment.comment_forum.commented_node.yml
new file mode 100644
index 0000000..9e10536
--- /dev/null
+++ b/core/modules/forum/config/optional/field.field.comment.comment_forum.commented_node.yml
@@ -0,0 +1,23 @@
+langcode: en
+status: true
+dependencies:
+  config:
+    - comment.type.comment_forum
+    - field.storage.comment.commented_node
+  module:
+    - entity_reference
+id: comment.comment_forum.commented_node
+field_name: commented_node
+entity_type: comment
+bundle: comment_forum
+label: Commented Node
+description: ''
+required: true
+translatable: false
+default_value: {  }
+default_value_callback: ''
+settings:
+  handler: 'default:node'
+  handler_settings: {  }
+third_party_settings: {  }
+field_type: entity_reference
diff --git a/core/modules/forum/config/optional/field.storage.comment.commented_node.yml b/core/modules/forum/config/optional/field.storage.comment.commented_node.yml
new file mode 100644
index 0000000..2b34306
--- /dev/null
+++ b/core/modules/forum/config/optional/field.storage.comment.commented_node.yml
@@ -0,0 +1,18 @@
+langcode: en
+status: true
+dependencies:
+  module:
+    - comment
+    - entity_reference
+id: comment.commented_node
+field_name: commented_node
+entity_type: comment
+type: entity_reference
+settings:
+  target_type: node
+module: entity_reference
+locked: true
+cardinality: 1
+translatable: false
+indexes: {  }
+persist_with_no_fields: true
diff --git a/core/modules/forum/src/ForumIndexStorage.php b/core/modules/forum/src/ForumIndexStorage.php
index 7994574..15aacbe 100644
--- a/core/modules/forum/src/ForumIndexStorage.php
+++ b/core/modules/forum/src/ForumIndexStorage.php
@@ -4,6 +4,7 @@
 use Drupal\comment\CommentInterface;
 use Drupal\Core\Database\Connection;
 use Drupal\node\NodeInterface;
+use Drupal\field\Entity\FieldStorageConfig;
 
 /**
  * Handles CRUD operations to {forum_index} table.
@@ -90,15 +91,18 @@ public function update(NodeInterface $node) {
    * {@inheritdoc}
    */
   public function updateIndex(NodeInterface $node) {
-    $nid = $node->id();
-    $count = $this->database->query("SELECT COUNT(cid) FROM {comment_field_data} c INNER JOIN {forum_index} i ON c.entity_id = i.nid WHERE c.entity_id = :nid AND c.field_name = 'comment_forum' AND c.entity_type = 'node' AND c.status = :status AND c.default_langcode = 1", [
+    $field_storage = FieldStorageConfig::loadByName('comment', 'commented_node');
+    $table_mapping = \Drupal::entityManager()->getStorage('comment')->getTableMapping();
+    $comment_entity_table = $table_mapping->getDedicatedDataTableName($field_storage);
+    $target_id_column = $table_mapping->getFieldColumnName($field_storage, 'target_id');
+    $count = $this->database->query("SELECT COUNT(cid) FROM {comment_field_data} c INNER JOIN {" . $comment_entity_table . "} ce ON c.cid = ce.entity_id AND ce.deleted = 0 INNER JOIN {forum_index} i ON ce." . $target_id_column . " = i.nid WHERE ce." . $target_id_column . " = :nid AND c.field_name = 'comment_forum' AND c.entity_type = 'node' AND c.status = :status AND c.default_langcode = 1", [
       ':nid' => $nid,
       ':status' => CommentInterface::PUBLISHED,
     ])->fetchField();
 
     if ($count > 0) {
       // Comments exist.
-      $last_reply = $this->database->queryRange("SELECT cid, name, created, uid FROM {comment_field_data} WHERE entity_id = :nid AND field_name = 'comment_forum' AND entity_type = 'node' AND status = :status AND default_langcode = 1 ORDER BY cid DESC", 0, 1, [
+      $last_reply = $this->database->queryRange("SELECT cid, name, created, uid FROM {comment_field_data} c INNER JOIN {" . $comment_entity_table . "} ce ON c.cid = ce.entity_id AND ce.deleted = 0  WHERE ce." . $target_id_column . " = :nid AND c.field_name = 'comment_forum' AND c.entity_type = 'node' AND c.status = :status AND c.default_langcode = 1 ORDER BY c.cid DESC", 0, 1, [
         ':nid' => $nid,
         ':status' => CommentInterface::PUBLISHED,
       ])->fetchObject();
diff --git a/core/modules/forum/src/ForumManager.php b/core/modules/forum/src/ForumManager.php
index 05cd860..64dfc4c 100644
--- a/core/modules/forum/src/ForumManager.php
+++ b/core/modules/forum/src/ForumManager.php
@@ -179,7 +179,7 @@ public function getTopics($tid, AccountInterface $account) {
         ->extend('Drupal\Core\Database\Query\TableSortExtender');
       $query->fields('n', ['nid']);
 
-      $query->join('comment_entity_statistics', 'ces', "n.nid = ces.entity_id AND ces.field_name = 'comment_forum' AND ces.entity_type = 'node'");
+      $query->join('comment_entity_statistics', 'ces', "CAST(n.nid AS CHAR(255)) = ces.entity_id AND ces.field_name = 'comment_forum' AND ces.entity_type = 'node'");
       $query->fields('ces', [
         'cid',
         'last_comment_uid',
@@ -335,7 +335,7 @@ protected function getLastPost($tid) {
     // Query "Last Post" information for this forum.
     $query = $this->connection->select('node_field_data', 'n');
     $query->join('forum', 'f', 'n.vid = f.vid AND f.tid = :tid', [':tid' => $tid]);
-    $query->join('comment_entity_statistics', 'ces', "n.nid = ces.entity_id AND ces.field_name = 'comment_forum' AND ces.entity_type = 'node'");
+    $query->join('comment_entity_statistics', 'ces', "CAST(n.nid AS CHAR(255)) = ces.entity_id AND ces.field_name = 'comment_forum' AND ces.entity_type = 'node'");
     $query->join('users_field_data', 'u', 'ces.last_comment_uid = u.uid AND u.default_langcode = 1');
     $query->addExpression('CASE ces.last_comment_uid WHEN 0 THEN ces.last_comment_name ELSE u.name END', 'last_comment_name');
 
@@ -373,7 +373,7 @@ protected function getForumStatistics($tid) {
     if (empty($this->forumStatistics)) {
       // Prime the statistics.
       $query = $this->connection->select('node_field_data', 'n');
-      $query->join('comment_entity_statistics', 'ces', "n.nid = ces.entity_id AND ces.field_name = 'comment_forum' AND ces.entity_type = 'node'");
+      $query->join('comment_entity_statistics', 'ces', "CAST(n.nid AS CHAR(255)) = ces.entity_id AND ces.field_name = 'comment_forum' AND ces.entity_type = 'node'");
       $query->join('forum', 'f', 'n.vid = f.vid');
       $query->addExpression('COUNT(n.nid)', 'topic_count');
       $query->addExpression('SUM(ces.comment_count)', 'comment_count');
diff --git a/core/modules/forum/src/Tests/Views/ForumIntegrationTest.php b/core/modules/forum/src/Tests/Views/ForumIntegrationTest.php
index f5677e4..6b10bd2 100644
--- a/core/modules/forum/src/Tests/Views/ForumIntegrationTest.php
+++ b/core/modules/forum/src/Tests/Views/ForumIntegrationTest.php
@@ -59,9 +59,9 @@ public function testForumIntegration() {
     $comments = [];
     foreach ($nodes as $index => $node) {
       for ($i = 0; $i <= $index; $i++) {
-        $comment = $comment_storage->create(['entity_type' => 'node', 'entity_id' => $node->id(), 'field_name' => 'comment_forum']);
+        $comment = $comment_storage->create(array('entity_type' => 'node', 'commented_node' => $node->id(), 'field_name' => 'comment_forum'));
         $comment->save();
-        $comments[$comment->get('entity_id')->target_id][$comment->id()] = $comment;
+        $comments[$comment->get('commented_node')->target_id][$comment->id()] = $comment;
       }
     }
 
diff --git a/core/modules/forum/tests/src/Functional/ForumBlockTest.php b/core/modules/forum/tests/src/Functional/ForumBlockTest.php
index 6c412b7..67af090 100644
--- a/core/modules/forum/tests/src/Functional/ForumBlockTest.php
+++ b/core/modules/forum/tests/src/Functional/ForumBlockTest.php
@@ -94,7 +94,7 @@ public function testActiveForumTopicsBlock() {
       $node = $this->drupalGetNodeByTitle($topics[$index]);
       $date->modify('+1 minute');
       $comment = Comment::create([
-        'entity_id' => $node->id(),
+        'commented_node' => $node->id(),
         'field_name' => 'comment_forum',
         'entity_type' => 'node',
         'node_type' => 'node_type_' . $node->bundle(),
diff --git a/core/modules/forum/tests/src/Functional/ForumUninstallTest.php b/core/modules/forum/tests/src/Functional/ForumUninstallTest.php
index c2d3848..e128000 100644
--- a/core/modules/forum/tests/src/Functional/ForumUninstallTest.php
+++ b/core/modules/forum/tests/src/Functional/ForumUninstallTest.php
@@ -52,7 +52,7 @@ public function testForumUninstallWithField() {
 
     // Create at least one comment against the forum node.
     $comment = Comment::create([
-      'entity_id' => $node->nid->value,
+      'commented_node' => $node->nid->value,
       'entity_type' => 'node',
       'field_name' => 'comment_forum',
       'pid' => 0,
diff --git a/core/modules/node/src/Tests/NodeAccessPagerTest.php b/core/modules/node/src/Tests/NodeAccessPagerTest.php
index b4fe830..ac03d07 100644
--- a/core/modules/node/src/Tests/NodeAccessPagerTest.php
+++ b/core/modules/node/src/Tests/NodeAccessPagerTest.php
@@ -42,7 +42,7 @@ public function testCommentPager() {
     // Create 60 comments.
     for ($i = 0; $i < 60; $i++) {
       $comment = Comment::create([
-        'entity_id' => $node->id(),
+        'commented_node' => $node->id(),
         'entity_type' => 'node',
         'field_name' => 'comment',
         'subject' => $this->randomMachineName(),
diff --git a/core/modules/rdf/rdf.module b/core/modules/rdf/rdf.module
index 0afcb09..6e30e9f 100644
--- a/core/modules/rdf/rdf.module
+++ b/core/modules/rdf/rdf.module
@@ -236,9 +236,13 @@ function rdf_comment_storage_load($comments) {
     /** @var \Drupal\comment\CommentInterface $comment*/
     $comment->rdf_data['date'] = rdf_rdfa_attributes($created_mapping, $comment->get('created')->first()->toArray());
     $entity = $comment->getCommentedEntity();
-    // The current function is a storage level hook, so avoid to bubble
-    // bubbleable metadata, because it can be outside of a render context.
-    $comment->rdf_data['entity_uri'] = $entity->toUrl()->toString(TRUE)->getGeneratedUrl();
+    // During comment_update_8302 the commented entity will temporarily not be
+    // available.
+    if ($entity) {
+      // The current function is a storage level hook, so avoid to bubble
+      // bubbleable metadata, because it can be outside of a render context.
+      $comment->rdf_data['entity_uri'] = $entity->toUrl()->toString(TRUE)->getGeneratedUrl();
+    }
     if ($comment->hasParentComment()) {
       $comment->rdf_data['pid_uri'] = $comment->getParentComment()->url();
     }
diff --git a/core/modules/rdf/src/Tests/CommentAttributesTest.php b/core/modules/rdf/src/Tests/CommentAttributesTest.php
index 8ca5798..9718c97 100644
--- a/core/modules/rdf/src/Tests/CommentAttributesTest.php
+++ b/core/modules/rdf/src/Tests/CommentAttributesTest.php
@@ -355,7 +355,7 @@ public function _testBasicCommentRdfaMarkup($graph, CommentInterface $comment, $
    */
   public function saveComment($nid, $uid, $contact = NULL, $pid = 0) {
     $values = [
-      'entity_id' => $nid,
+      'commented_node' => $nid,
       'entity_type' => 'node',
       'field_name' => 'comment',
       'uid' => $uid,
diff --git a/core/modules/rdf/tests/src/Functional/StandardProfileTest.php b/core/modules/rdf/tests/src/Functional/StandardProfileTest.php
index 76ae39b..4ba594b 100644
--- a/core/modules/rdf/tests/src/Functional/StandardProfileTest.php
+++ b/core/modules/rdf/tests/src/Functional/StandardProfileTest.php
@@ -500,7 +500,7 @@ protected function assertRdfaNodeCommentProperties($graph) {
    */
   protected function saveComment($nid, $uid, $contact = NULL, $pid = 0) {
     $values = [
-      'entity_id' => $nid,
+      'commented_node' => $nid,
       'entity_type' => 'node',
       'field_name' => 'comment',
       'uid' => $uid,
diff --git a/core/modules/system/tests/src/Functional/Entity/EntityReferenceSelection/EntityReferenceSelectionAccessTest.php b/core/modules/system/tests/src/Functional/Entity/EntityReferenceSelection/EntityReferenceSelectionAccessTest.php
index df33102..bde1477 100644
--- a/core/modules/system/tests/src/Functional/Entity/EntityReferenceSelection/EntityReferenceSelectionAccessTest.php
+++ b/core/modules/system/tests/src/Functional/Entity/EntityReferenceSelection/EntityReferenceSelectionAccessTest.php
@@ -393,7 +393,7 @@ public function testCommentHandler() {
 
     $comment_values = [
       'published_published' => [
-        'entity_id' => $nodes['published']->id(),
+        'commented_node' => $nodes['published']->id(),
         'entity_type' => 'node',
         'field_name' => 'comment',
         'uid' => 1,
@@ -404,7 +404,7 @@ public function testCommentHandler() {
         'language' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
       ],
       'published_unpublished' => [
-        'entity_id' => $nodes['published']->id(),
+        'commented_node' => $nodes['published']->id(),
         'entity_type' => 'node',
         'field_name' => 'comment',
         'uid' => 1,
@@ -415,7 +415,7 @@ public function testCommentHandler() {
         'language' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
       ],
       'unpublished_published' => [
-        'entity_id' => $nodes['unpublished']->id(),
+        'commented_node' => $nodes['published']->id(),
         'entity_type' => 'node',
         'field_name' => 'comment',
         'uid' => 1,
diff --git a/core/modules/tracker/tracker.module b/core/modules/tracker/tracker.module
index dbde704..29a3fea 100644
--- a/core/modules/tracker/tracker.module
+++ b/core/modules/tracker/tracker.module
@@ -95,7 +95,7 @@ function tracker_cron() {
       // so don't add an aggregate field.
       $result = \Drupal::entityQueryAggregate('comment')
         ->condition('entity_type', 'node')
-        ->condition('entity_id', $node->id())
+        ->condition('commented_node', $node->id())
         ->condition('uid', $node->getOwnerId(), '<>')
         ->condition('status', CommentInterface::PUBLISHED)
         ->groupBy('uid')
@@ -323,7 +323,7 @@ function _tracker_remove($nid, $uid = NULL, $changed = NULL) {
       // Check if the user has commented at least once on the given nid.
       $keep_subscription = \Drupal::entityQuery('comment')
         ->condition('entity_type', 'node')
-        ->condition('entity_id', $nid)
+        ->condition('commented_node', $nid)
         ->condition('uid', $uid)
         ->condition('status', CommentInterface::PUBLISHED)
         ->range(0, 1)
diff --git a/core/modules/views/src/Tests/DefaultViewsTest.php b/core/modules/views/src/Tests/DefaultViewsTest.php
index 48e3cae..e3c3cff 100644
--- a/core/modules/views/src/Tests/DefaultViewsTest.php
+++ b/core/modules/views/src/Tests/DefaultViewsTest.php
@@ -95,7 +95,7 @@ protected function setUp() {
       $comment = [
         'uid' => $user->id(),
         'status' => CommentInterface::PUBLISHED,
-        'entity_id' => $node->id(),
+        'commented_node' => $node->id(),
         'entity_type' => 'node',
         'field_name' => 'comment'
       ];
diff --git a/core/modules/views/src/Tests/Entity/FieldEntityTest.php b/core/modules/views/src/Tests/Entity/FieldEntityTest.php
index 89f71ed..c1b0170 100644
--- a/core/modules/views/src/Tests/Entity/FieldEntityTest.php
+++ b/core/modules/views/src/Tests/Entity/FieldEntityTest.php
@@ -63,7 +63,7 @@ public function testGetEntity() {
     $node->save();
     $comment = Comment::create([
       'uid' => $account->id(),
-      'entity_id' => $node->id(),
+      'commented_node' => $node->id(),
       'entity_type' => 'node',
       'field_name' => 'comment'
     ]);
diff --git a/core/modules/views/src/Tests/Handler/HandlerTest.php b/core/modules/views/src/Tests/Handler/HandlerTest.php
index e07beb3..228a6fc 100644
--- a/core/modules/views/src/Tests/Handler/HandlerTest.php
+++ b/core/modules/views/src/Tests/Handler/HandlerTest.php
@@ -269,25 +269,25 @@ public function testRelationshipUI() {
         $options[] = $item->attributes()->value;
       }
     }
-    $expected_options = ['none', 'nid'];
+    $expected_options = array('none', 'commented_node');
     $this->assertEqual($options, $expected_options);
 
     // Remove the relationship and make sure no relationship option appears.
-    $this->drupalPostForm('admin/structure/views/nojs/handler/test_handler_relationships/default/relationship/nid', [], t('Remove'));
+    $this->drupalPostForm('admin/structure/views/nojs/handler/test_handler_relationships/default/relationship/commented_node', array(), t('Remove'));
     $this->drupalGet($handler_options_path);
     $this->assertNoFieldByName($relationship_name, NULL, 'Make sure that no relationship option is available');
 
     // Create a view of comments with node relationship.
     View::create(['base_table' => 'comment_field_data', 'id' => 'test_get_entity_type'])->save();
-    $this->drupalPostForm('admin/structure/views/nojs/add-handler/test_get_entity_type/default/relationship', ['name[comment_field_data.node]' => 'comment_field_data.node'], t('Add and configure relationships'));
+    $this->drupalPostForm('admin/structure/views/nojs/add-handler/test_get_entity_type/default/relationship', ['name[comment__commented_node.commented_node]' => 'comment__commented_node.commented_node'], t('Add and configure relationships'));
     $this->drupalPostForm(NULL, [], t('Apply'));
     // Add a content type filter.
     $this->drupalPostForm('admin/structure/views/nojs/add-handler/test_get_entity_type/default/filter', ['name[node_field_data.type]' => 'node_field_data.type'], t('Add and configure filter criteria'));
-    $this->assertOptionSelected('edit-options-relationship', 'node');
+    $this->assertOptionSelected('edit-options-relationship', 'commented_node');
     $this->drupalPostForm(NULL, ['options[value][page]' => 'page'], t('Apply'));
     // Check content type filter options.
     $this->drupalGet('admin/structure/views/nojs/handler/test_get_entity_type/default/filter/type');
-    $this->assertOptionSelected('edit-options-relationship', 'node');
+    $this->assertOptionSelected('edit-options-relationship', 'commented_node');
     $this->assertFieldChecked('edit-options-value-page');
   }
 
@@ -300,7 +300,7 @@ public function testSetRelationship() {
     // Setup a broken relationship.
     $view->addHandler('default', 'relationship', $this->randomMachineName(), $this->randomMachineName(), [], 'broken_relationship');
     // Setup a valid relationship.
-    $view->addHandler('default', 'relationship', 'comment_field_data', 'node', ['relationship' => 'cid'], 'valid_relationship');
+    $view->addHandler('default', 'relationship', 'comment__commented_node', 'commented_node', array('relationship' => 'reverse__comment__commented_node'), 'valid_relationship');
     $view->initHandlers();
     $field = $view->field['title'];
 
diff --git a/core/modules/views/tests/modules/views_test_config/test_views/views.view.test_destroy.yml b/core/modules/views/tests/modules/views_test_config/test_views/views.view.test_destroy.yml
index 035d40f..f303ced 100644
--- a/core/modules/views/tests/modules/views_test_config/test_views/views.view.test_destroy.yml
+++ b/core/modules/views/tests/modules/views_test_config/test_views/views.view.test_destroy.yml
@@ -170,22 +170,27 @@ display:
       query:
         type: views_query
       relationships:
-        comment_cid:
-          field: comment_cid
-          id: comment_cid
+        reverse__comment__commented_node:
+          id: reverse__comment__commented_node
           table: node_field_data
-          plugin_id: standard
+          field: reverse__comment__commented_node
+          relationship: none
+          group_type: group
+          admin_label: Comments
+          required: false
+          entity_type: node
+          plugin_id: entity_reverse
         pid:
           field: pid
           id: pid
           table: comment_field_data
-          relationship: comment_cid
+          relationship: reverse__comment__commented_node
           plugin_id: standard
         uid:
           field: uid
           id: uid
           table: comment_field_data
-          relationship: comment_cid
+          relationship: reverse__comment__commented_node
           plugin_id: standard
       sorts:
         last_comment_name:
diff --git a/core/modules/views/tests/modules/views_test_config/test_views/views.view.test_field_get_entity.yml b/core/modules/views/tests/modules/views_test_config/test_views/views.view.test_field_get_entity.yml
index cc3b66c..20e790c 100644
--- a/core/modules/views/tests/modules/views_test_config/test_views/views.view.test_field_get_entity.yml
+++ b/core/modules/views/tests/modules/views_test_config/test_views/views.view.test_field_get_entity.yml
@@ -34,7 +34,7 @@ display:
           field: nid
           id: nid
           table: node_field_data
-          relationship: node
+          relationship: commented_node
           plugin_id: field
           entity_type: node
           entity_field: nid
@@ -55,18 +55,21 @@ display:
       query:
         type: views_query
       relationships:
-        node:
-          field: node
-          id: node
+        commented_node:
+          id: commented_node
+          table: comment__commented_node
+          field: commented_node
+          relationship: none
+          group_type: group
+          admin_label: 'commented_node: Content'
           required: true
-          table: comment_field_data
           plugin_id: standard
         uid:
           admin_label: Author
           field: uid
           group_type: group
           id: uid
-          relationship: node
+          relationship: commented_node
           required: false
           table: node_field_data
           plugin_id: standard
diff --git a/core/modules/views/tests/modules/views_test_config/test_views/views.view.test_handler_relationships.yml b/core/modules/views/tests/modules/views_test_config/test_views/views.view.test_handler_relationships.yml
index 1c4c7ac..38b278b 100644
--- a/core/modules/views/tests/modules/views_test_config/test_views/views.view.test_handler_relationships.yml
+++ b/core/modules/views/tests/modules/views_test_config/test_views/views.view.test_handler_relationships.yml
@@ -23,16 +23,24 @@ display:
           entity_type: node
           entity_field: title
       relationships:
-        comment_cid:
-          id: comment_cid
+        reverse__comment__commented_node:
+          id: reverse__comment__commented_node
           table: node_field_data
-          field: comment_cid
-          plugin_id: standard
-        nid:
-          id: nid
-          table: comment_field_data
-          field: node
-          relationship: comment_cid
+          field: reverse__comment__commented_node
+          relationship: none
+          group_type: group
+          admin_label: Comments
+          required: false
+          entity_type: node
+          plugin_id: entity_reverse
+        commented_node:
+          id: commented_node
+          table: comment__commented_node
+          field: commented_node
+          relationship: reverse__comment__commented_node
+          group_type: group
+          admin_label: Content
+          required: false
           plugin_id: standard
     display_plugin: default
     display_title: Master
diff --git a/core/modules/views/tests/modules/views_test_config/test_views/views.view.test_relationship_dependency.yml b/core/modules/views/tests/modules/views_test_config/test_views/views.view.test_relationship_dependency.yml
index f392a52..db561ca 100644
--- a/core/modules/views/tests/modules/views_test_config/test_views/views.view.test_relationship_dependency.yml
+++ b/core/modules/views/tests/modules/views_test_config/test_views/views.view.test_relationship_dependency.yml
@@ -39,10 +39,13 @@ display:
       query:
         type: views_query
       relationships:
-        node:
-          field: node
-          id: node
-          table: comment_field_data
+        commented_node:
+          id: commented_node
+          table: comment__commented_node
+          field: commented_node
+          relationship: none
+          group_type: group
+          admin_label: 'commented_node: Content'
           required: true
           plugin_id: standard
       sorts: {  }
diff --git a/core/modules/views/tests/src/Kernel/Entity/ViewEntityDependenciesTest.php b/core/modules/views/tests/src/Kernel/Entity/ViewEntityDependenciesTest.php
index 4929c7e..7bc3305 100644
--- a/core/modules/views/tests/src/Kernel/Entity/ViewEntityDependenciesTest.php
+++ b/core/modules/views/tests/src/Kernel/Entity/ViewEntityDependenciesTest.php
@@ -49,6 +49,7 @@ protected function setUp($import_test_views = TRUE) {
       'target_entity_type_id' => 'node',
     ]);
     $comment_type->save();
+    \Drupal::service('comment.manager')->addEntityField('comment');
 
     $content_type = NodeType::create([
       'type' => $this->randomMachineName(),
diff --git a/core/profiles/standard/config/install/field.field.comment.comment.commented_node.yml b/core/profiles/standard/config/install/field.field.comment.comment.commented_node.yml
new file mode 100644
index 0000000..a579ec5
--- /dev/null
+++ b/core/profiles/standard/config/install/field.field.comment.comment.commented_node.yml
@@ -0,0 +1,23 @@
+langcode: en
+status: true
+dependencies:
+  config:
+    - comment.type.comment
+    - field.storage.comment.commented_node
+  module:
+    - entity_reference
+id: comment.comment.commented_node
+field_name: commented_node
+entity_type: comment
+bundle: comment
+label: Commented Node
+description: ''
+required: true
+translatable: false
+default_value: {  }
+default_value_callback: ''
+settings:
+  handler: 'default:node'
+  handler_settings: {  }
+third_party_settings: {  }
+field_type: entity_reference
diff --git a/core/profiles/standard/config/install/field.storage.comment.commented_node.yml b/core/profiles/standard/config/install/field.storage.comment.commented_node.yml
new file mode 100644
index 0000000..2b34306
--- /dev/null
+++ b/core/profiles/standard/config/install/field.storage.comment.commented_node.yml
@@ -0,0 +1,18 @@
+langcode: en
+status: true
+dependencies:
+  module:
+    - comment
+    - entity_reference
+id: comment.commented_node
+field_name: commented_node
+entity_type: comment
+type: entity_reference
+settings:
+  target_type: node
+module: entity_reference
+locked: true
+cardinality: 1
+translatable: false
+indexes: {  }
+persist_with_no_fields: true
-- 
2.5.4 (Apple Git-61)

