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);

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

  Work with me!

<?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 int PROPERTIES_COUNT = 22;
    private const int 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);
    }
}

Call to action

Did you like this post? You can help me back in several ways: (use the "reply" link on the right to comment or to contact me )

Thank you for reading! And see you soon on Strangebuzz! 😉

COil