Entity Query custom fields

Last updated on
14 March 2025

This documentation needs review. See "Help improve this page" in the sidebar.

Generally speaking, querying for custom field properties are no different than querying for any other type of field properties but there are scenarios where some differences in how you query are required. One such case is when you have a custom field entity_reference subfield type and you want to query on fields on the actual entity being referenced. 

Let's assume you have a custom field type named field_custom and a subfield of type entity_reference named reference which can reference nodes. The nodes have a field called field_number that you want to filter by in your query. With a normal entity reference field in an entity query, we could do something like this to get the nested field value of the referenced node:

$query = \Drupal::entityQuery('node')
  ->condition('type', 'article')
  ->condition('field_reference.entity.field_number', 5);

This works because the field_reference entity reference field has a main property on the target_id and the computed entity property along with the handler settings defined in the field definition can resolve to an entity and therefore drill down to the field_number value.

In custom_field types however, there is not a main property entityQuery to work with therefore cannot derive the values in the same way. The custom_field way of doing this for the same scenario would look like this:

$query = \Drupal::entityQuery('node')
  ->condition('type', 'article')
  ->condition('field_custom.reference.reference__entity:node.field_number', 5);

This works for the following reasons:

  • field_custom is used as the base table
  • Although the main property is null, the next specifier reference is a real column that takes precedence and the key is advanced
  • Every entity_reference subfield has a computed property for the entity with the syntax of {subfield_name}__entity which in this case results in reference__entity
  •  reference__entity:node is used as the relationship_specifier. Since it's in the property definitions and is type DataReferenceDefinitionInterface, it joins the node table.

Help improve this page

Page status: Needs review

You can: