2011-11-23 70 views
35

你知道如何从实体声明在我的控制器类获得表名获取实体类的表名

实体类

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

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

回答

80

从控制器中你可以使用:

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

注意,getClassMetadata方法返回了一堆关于实体的有趣的信息。

+1

如何连接表名?你知道如何得到它吗? –

+5

使用php 5.5+,你可以使用内置类constant :: class。 '''$ tableName = $ em-> getClassMetadata(User :: class) - > getTableName();''' –

0

随着Symfony的2.3 &学说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); 
    } 

} 
2

我需要找出一个映射表的名称(使用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'];