获取实体类的表名

时间:2011-11-23 14:19:33

标签: symfony doctrine-orm

您知道如何从我的控制器类

中的实体声明中获取表名

实体类

<?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

我现在想获取User实体的表名,我将如何在Symfony2控制器中执行此操作?

3 个答案:

答案 0 :(得分:97)

在控制器中使用:

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

请注意,getClassMetadata方法会返回一堆有关该实体的有趣信息。

答案 1 :(得分:4)

我需要找出多对多关系中的映射表的名称(使用FOSUserBundle)。也许这有助于某人:

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

答案 2 :(得分:0)

使用Symfony 2.3&amp;学说2这对我有用:

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

}