When adding a relationship in views on an entity reference base field that has a cardinality that is unlimited (or larger than one) the query fires an sql error

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'entity_table__referenced_entity.referenced_entity' in 'where clause': SELECT entity_table.created AS entity_table_created, entity_table.id AS id FROM {entity_table} entity_table LEFT JOIN {entity_table__referenced_entity} entity_table__referenced_entity ON entity_table.id = entity_table__referenced_entity.entity_id AND entity_table__referenced_entity.deleted = :views_join_condition_0 WHERE (( (entity_table__referenced_entity.referenced_entity = :db_condition_placeholder_1) )) ORDER BY entity_table_created DESC LIMIT 6 OFFSET 0; Array ( [:db_condition_placeholder_1] => 1 [:views_join_condition_0] => 0 )

From what i can tell the join is done on the inexistent field
entity_table__referenced_entity.referenced_entity instead of entity_table__referenced_entity.referenced_entity_target_id

This happens only when the field is a base field. I have replicated the conditions with the same field added to a bundle of the entity and the join is made on the correct field and the query runs correctly

Steps to reproduce:
1. Define a custom content entity type
2. Attach to it an entity reference field as a base field. Set cardinality to -1.
3. Make a view of items of that entity and add a relation to the entity type referenced in the field

Comments

adrianghe created an issue. See original summary.

jhedstrom’s picture

Issue tags: +VDC
geekygnr’s picture

Version: 8.1.9 » 8.2.3

After finding this problem I updated to 8.2.3 in hopes that a fix was given but it seems to have the same problem.

geekygnr’s picture

I tried to do this

diff --git a/core/modules/views/src/Plugin/views/relationship/RelationshipPluginBase.php b/core/modules/views/src/Plugin/views/relationship/RelationshipPluginBase.php
index 25a0001..c910d3a 100644
--- a/core/modules/views/src/Plugin/views/relationship/RelationshipPluginBase.php
+++ b/core/modules/views/src/Plugin/views/relationship/RelationshipPluginBase.php
@@ -135,7 +135,7 @@ public function query() {
     $def['table'] = $this->definition['base'];
     $def['field'] = $base_field;
     $def['left_table'] = $this->tableAlias;
-    $def['left_field'] = $this->realField;
+    $def['left_field'] = $this->realField . '_target_id';
     $def['adjusted'] = TRUE;
     if (!empty($this->options['required'])) {
       $def['type'] = 'INNER';

But it was breaking so many tests that I am not sure if this is where the actual problem is. It could be a problem with the entity definition or how the entities are created once defined.

geekygnr’s picture

Status: Active » Closed (duplicate)