Matt
Matt

Reputation: 2843

Get table name of entity class

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?

Upvotes: 60

Views: 47153

Answers (3)

con
con

Reputation: 2410

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'];

Upvotes: 7

Steven Mercatante
Steven Mercatante

Reputation: 25295

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.

Upvotes: 134

herrjeh42
herrjeh42

Reputation: 2793

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

}

Upvotes: 0

Related Questions