You are here

public function SelectSubqueryTest::testConditionSubquerySelect2 in Drupal 9

Same name and namespace in other branches
  1. 8 core/tests/Drupal/KernelTests/Core/Database/SelectSubqueryTest.php \Drupal\KernelTests\Core\Database\SelectSubqueryTest::testConditionSubquerySelect2()

Tests that we can use a subquery with a relational operator in a WHERE clause.

File

core/tests/Drupal/KernelTests/Core/Database/SelectSubqueryTest.php, line 103

Class

SelectSubqueryTest
Tests the Select query builder.

Namespace

Drupal\KernelTests\Core\Database

Code

public function testConditionSubquerySelect2() {

  // Create a subquery, which is just a normal query object.
  $subquery = $this->connection
    ->select('test', 't2');
  $subquery
    ->addExpression('AVG([t2].[age])');

  // Create another query that adds a clause using the subquery.
  $select = $this->connection
    ->select('test', 't');
  $select
    ->addField('t', 'name');
  $select
    ->condition('t.age', $subquery, '<');

  // The resulting query should be equivalent to:
  // SELECT t.name
  // FROM test t
  // WHERE t.age < (SELECT AVG(t2.age) FROM test t2)
  $people = $select
    ->execute()
    ->fetchCol();
  $this
    ->assertEqualsCanonicalizing([
    'John',
    'Paul',
  ], $people, 'Returned Paul and John.');
}