Getting the fields and associations list of a Doctrine entity

Published on 2020-08-01 • Modified on 2020-08-01

In this snippet, we will see how to get the fields and associations list of a Doctrine entity. First, we get the meta class of the entity we want to analyse by passing its FQCN to the Doctrine manager getClassMetadata() method. Then, we can get the information with two dedicated methods.


<?php

declare(strict_types=1);

// src/Controller/Snippet/Snippet107Trait.php

namespace App\Controller\Snippet;

use App\Entity\Article;
use Doctrine\ORM\EntityManagerInterface;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 *
 * @property EntityManagerInterface $entityManager
 */
trait Snippet107Trait
{
    public function snippet107(): void
    {
        $articleMetaData = $this->entityManager->getClassMetadata(Article::class);
        var_dump($articleMetaData->getFieldNames());
        var_dump($articleMetaData->getAssociationNames());

        // That's it! 😁
    }
}

 Run this snippet  ≪ this.showUnitTest ? this.trans.hide_unit_test : this.trans.show_unit_test ≫  More on Stackoverflow   Read the doc  Random snippet

<?php

declare(strict_types=1);

namespace App\Tests\Integration\Controller\Snippets;

use App\Entity\Article;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

/**
 * @see Snippet107Trait
 */
final class Snippet107Test extends KernelTestCase
{
    private const PROPERTIES_COUNT = 23;
    private const ASSOCIATIONS_COUNT = 4;

    private EntityManagerInterface $em;

    protected function setUp(): void
    {
        $this->em = self::getContainer()->get(EntityManagerInterface::class);
    }

    /**
     * @see Snippet107Trait::snippet107
     */
    public function testSnippet107(): void
    {
        $articleMetaData = $this->em->getClassMetadata(Article::class);
        $properties = $articleMetaData->getFieldNames();
        $associations = $articleMetaData->getAssociationNames();
        self::assertIsArray($properties);
        self::assertIsArray($associations);
        self::assertCount(self::PROPERTIES_COUNT, $properties);
        self::assertCount(self::ASSOCIATIONS_COUNT, $associations);
    }
}