0

Let's say I have a node type named 'Book'. 'Book' nodes have 'publisher' field. I want to create a node view which displays these two columns:

  • book title
  • title of a book published by the same publisher

enter image description here

Desired results is like this. book view

The problem is I cannot use entity reverse relationship which is normally used to connect entities because 'publisher' field is not entity reference field.

So I added the code to my_module.views.inc.

funciton my_module_views_data() {
  // it seems first node's 'node__field_publisher' is already loaded, so join second node's node_field_data directly. 
  $data['node__field_publisher']['node_field_data'] = [
    'title' => t('Same publisher books'),
    'help' => t('Get books sharing publisher'),
    'relationship' => [
      'id' => 'standard',
      'label' => 'Same publisher books',
      'left_table' => 'node__field_publisher',
      'field' => 'entity_id',
      'base' => 'node_field_data',
      'base field' => 'nid',
    ],
  ];
}

It created join and relationship 'Same publisher books' became available.

LEFT JOIN {node_field_data} node_field_data_node__field_publisher ON node__field_publisher.entity_id = node_field_data_node__field_publisher.nid

If I click 'Add' in 'field section', select 'Title', set 'Same publisher books' as 'relationship', it adds query to SELECT statement like this

node_field_data_node__field_publisher.nid AS node_field_data_node__field_publisher_nid

But no titles.

I thought if I make a relationship to other node, it automatically loads field values belonging to the node(e.g. title), but is it a misconception?
How to get titles in this case?

1
  • IIUIC Relationships pull information from other tables from the database, initially Views can "see" only the info from the "base" table, the type you choose when creating Views (content, user, taxonomy term). Can't you list all the book nodes with Title and Publisher fields, then use grouping under Format, group by the Publisher field. Why would you want the main book title to be repeated? Entity reference fields are built for this purpose, why not use them? Are you planning on using Contextual fitlers to place this info on bok pages? – prkos Apr 18 at 7:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.