function EntityQueryTest::testWithTwoEntityReferenceFieldsToSameEntityType

Same name and namespace in other branches
  1. 11.x core/tests/Drupal/KernelTests/Core/Entity/EntityQueryTest.php \Drupal\KernelTests\Core\Entity\EntityQueryTest::testWithTwoEntityReferenceFieldsToSameEntityType()
  2. 9 core/tests/Drupal/KernelTests/Core/Entity/EntityQueryTest.php \Drupal\KernelTests\Core\Entity\EntityQueryTest::testWithTwoEntityReferenceFieldsToSameEntityType()
  3. 8.9.x core/tests/Drupal/KernelTests/Core/Entity/EntityQueryTest.php \Drupal\KernelTests\Core\Entity\EntityQueryTest::testWithTwoEntityReferenceFieldsToSameEntityType()

Tests that EntityQuery works when querying the same entity from two fields.

File

core/tests/Drupal/KernelTests/Core/Entity/EntityQueryTest.php, line 1242

Class

EntityQueryTest
Tests Entity Query functionality.

Namespace

Drupal\KernelTests\Core\Entity

Code

public function testWithTwoEntityReferenceFieldsToSameEntityType() : void {
  // Create two entity reference fields referring 'entity_test' entities.
  $this->createEntityReferenceField('entity_test', 'entity_test', 'ref1', $this->randomMachineName(), 'entity_test');
  $this->createEntityReferenceField('entity_test', 'entity_test', 'ref2', $this->randomMachineName(), 'entity_test');
  $storage = $this->container
    ->get('entity_type.manager')
    ->getStorage('entity_test');
  // Create two entities to be referred.
  $ref1 = EntityTest::create([
    'type' => 'entity_test',
  ]);
  $ref1->save();
  $ref2 = EntityTest::create([
    'type' => 'entity_test',
  ]);
  $ref2->save();
  // Create a main entity referring the previous created entities.
  $entity = EntityTest::create([
    'type' => 'entity_test',
    'ref1' => $ref1->id(),
    'ref2' => $ref2->id(),
  ]);
  $entity->save();
  // Check that works when referring with "{$field_name}".
  $result = $storage->getQuery()
    ->accessCheck(FALSE)
    ->condition('type', 'entity_test')
    ->condition('ref1', $ref1->id())
    ->condition('ref2', $ref2->id())
    ->execute();
  $this->assertCount(1, $result);
  $this->assertEquals($entity->id(), reset($result));
  // Check that works when referring with "{$field_name}.target_id".
  $result = $storage->getQuery()
    ->accessCheck(FALSE)
    ->condition('type', 'entity_test')
    ->condition('ref1.target_id', $ref1->id())
    ->condition('ref2.target_id', $ref2->id())
    ->execute();
  $this->assertCount(1, $result);
  $this->assertEquals($entity->id(), reset($result));
  // Check that works when referring with "{$field_name}.entity.id".
  $result = $storage->getQuery()
    ->accessCheck(FALSE)
    ->condition('type', 'entity_test')
    ->condition('ref1.entity.id', $ref1->id())
    ->condition('ref2.entity.id', $ref2->id())
    ->execute();
  $this->assertCount(1, $result);
  $this->assertEquals($entity->id(), reset($result));
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.