2011-11-23 36 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']; 
相關問題