Get table name of entity class

SymfonyDoctrine Orm

Symfony Problem Overview


Do you know how to get the table name from an Entity declaration in my controller class

Entity Class

<?php

namespace Acme\StoreBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Acme\StoreBundle\Entity\User
 *
 * @ORM\Table(name="users")
 * @ORM\Entity
 */
class User

I now would like to get the table name of the User entity, how would i do this in my Symfony2 controller?

Symfony Solutions


Solution 1 - Symfony

From within a controller you would use:

$em = $this->getDoctrine()->getManager();
$tableName = $em->getClassMetadata('StoreBundle:User')->getTableName();

Note that the getClassMetadata method returns a bunch of interesting info about the entity.

Solution 2 - Symfony

I needed to find out the name of a mapping Table in a many-to-many relationship (using FOSUserBundle). Maybe this helps someone:

    $groupAssociation = $this->getEntityManager()
                             ->getClassMetadata('UOACLBundle:User')
                             ->getAssociationsByTargetClass(Group::class);

    // 'groups' is the name of the property in my User Class
    $mappingTable = $groupAssociation['groups']['joinTable']['name'];

Solution 3 - Symfony

With Symfony 2.3 & Doctrine 2 this worked for me:

// my entity is called "Record"
// Acme/DemoBundle/Entity/RecordRepository.php
class RecordRepository extends EntityRepository
{

     /**
     * Sets the primary table definition. The provided array supports the
     * following structure:
     *
     * name => <tableName> (optional, defaults to class name)
     * indexes => array of indexes (optional)
     * uniqueConstraints => array of constraints (optional)
     *
     * If a key is omitted, the current value is kept.
     *
     * @param array $table The table description.
     */
    public function setDataTableName($tableInfo) {
        return $this->getEntityManager()->getClassMetadata('AcmeDemoBundle:Record')->setPrimaryTable($tableInfo);
    }

}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMattView Question on Stackoverflow
Solution 1 - SymfonySteven MercatanteView Answer on Stackoverflow
Solution 2 - SymfonyconView Answer on Stackoverflow
Solution 3 - Symfonyherrjeh42View Answer on Stackoverflow