DrupalX

Extension
Framework

query

Factory

Factory

This method can be used to search for entities by various conditions. In contrast to Drupal 8's native "Entity query" mechanism, using this method is much simpler due to the more concise syntax and overall usage. In contrast to "queryAll", this method will just return the first item found.

The query, given here as the first argument, is basically just a simple associative array. In the following example we're searching for a blue car. Please note that the Entity class is usually not used directly but always one of its sub-classes (Node, Paragraph, ...):

{% set node=Node::queryAll{type:"product",color:"blue"} %}
Blue Car: {{node.title}}

We might extend this now with so-called operator codes to search for all cars that are NOT blue. These codes are simply appended to the key. Please note that now the quotes around the key are becoming necessary even in Twig (in PHP anyway) since the key isn't exclusively alpha-numeric anymore:

{% set node=Node::queryAll{type:"product","color!":"blue"} %}
This car is not blue: {{node.title}}

The additional exclamation mark (i.e. "NOT") will now invert the query.

The following tables will give you an overview over all DrupalX operator codes. Which operator codes are available depends on the type of value specified. There is one set of allowed operator codes for scalar values (like the value "blue" in the example given above) or array values like in the following example which searches for all cars not red and not blue:

{% set node=Node::queryAll{type:"product","color!":["red","blue"]} %}
This car is not red and not blue: {{node.title}}

Value is a scalar (String, Integer etc.)

DrupalX operator code Description
= (or, alternatively, ==), can be completely omitted (default) is equal to
! (or, alternatively, <>) is not equal to
> is greater than
>= is greater than or equal to
< is less than
<= is less than or equal to
>. (or, alternatively, >..) begins with
<. (or, alternatively, ..<) ends with
.v. (or, alternatively, .V.) contains

Value is an array

DrupalX operator code Description
= (or, alternatively, ==), can be completely omitted (default) is in
! (or, alternatively, <>) is not in
>< (or, alternatively, >.< or >..<) is between