It would be useful to be able to select bundle(s) when adding an entity reference relationship to a view.

Use Case 1:

I'm trying to show all nodes that don't have other entities of a certain type referencing them. Currently there's no way to do this, since this has to happen on the join, not as a condition. E.g., I need SQL like:

SELECT *
FROM node
LEFT JOIN field_data_field_reference fr ON node.nid = fr.nid AND fr.bundle = 'bundle-type'
GROUP BY node.nid
HAVING COUNT(fr.nid) = 0

If a condition (filter) is added, then it will always return no results, since it forces the join.

Use Case 2:

When a list of Nodes of a type is requested by relationship in a View
And when multiple entity types (Node and User) share a common entity reference field
And when User ID (entity_id == uid) and Node ID (entity_id == nid) happen to be the same
Then unexpected, extraneous entities will show in the result.
Expected: Only a certain subset of the nodes is expected.

Instead: If a site builder could limit the requested relationship down to bundle, then only the expected nodes would be returned.

Comments

duellj’s picture

My temporary solution was to implement hook_views_query_alter():

function mymodule_views_query_alter(&$view, &$query) {
  if ($view->name == 'your-view') {
    if (isset($query->table_queue['field_data_field_reference'])) {
      $query->table_queue['field_data_field_question']['join']->extra[] = array(
        'field' => 'bundle',
        'value' => 'bundle-type',
      );
    }
  }
}
relaxnow’s picture

Issue summary: View changes

I'm having the same need for a project where I'm referencing multiple bundles with a single entity reference but would like to COUNT by bundle with a view.

texas-bronius’s picture

Thanks @duellj for sharing this easy, perfect solution. I put it in my custom module, changed both "field_data_field_.." lines to the same name of the table for the reference, et voila, views reference was limited by bundle. Helped, in my case, where autoincrement users->uid caught up to node->nid, and I started seeing unexpected entities in the Views output.

texas-bronius’s picture

Title: Provide a way to limit views releationship by bundle » Entity Reference: Add option to limit Views relationship results by bundle
Issue summary: View changes