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\Bundle\DoctrineBundle\Registry;

/**
 * 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.
 */
trait Snippet107Trait
{
    public function snippet107(): void
    {
        $doctrine = $this->getDoctrine();
        if (!$doctrine instanceof Registry) {
            throw new \RuntimeException("Houston, We've Got a Problem. 💥");
        }

        $articleMetaData = $doctrine->getManager()->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\Controller\Snippets;

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

/**
 * @covers Snippet107Trait
 */
final class Snippet107Test extends KernelTestCase
{
    private EntityManagerInterface $em;

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

    /**
     * @covers 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(17, $properties);
        self::assertCount(5, $associations);
    }
}