2011-11-23 19 views
35

Sai come ottenere il nome della tabella da una dichiarazione di entità nella mia classe controllerOttenere il nome della tabella di classe di entità

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 

ora mi piacerebbe avere il nome della tabella della Entità utente, come lo farei nel mio controller Symfony2?

risposta

80

Dall'interno di un controller che si potrebbe usare:

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

Si noti che il metodo getClassMetadata restituisce un po 'di informazioni interessanti circa l'entità.

+1

Che ne dici del nome della tabella di join? Sai come ottenerlo? –

+5

Con php 5.5+ è possibile utilizzare la costante :: class di classe integrata. '' '$ tableName = $ em-> getClassMetadata (User :: class) -> getTableName();' '' –

0

Con Symfony 2.3 & Doctrine 2 questo ha funzionato per 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); 
    } 

} 
2

avevo bisogno di scoprire il nome di una tabella di mappatura in una relazione molti-a-molti (usando FOSUserBundle). Forse questo aiuta qualcuno:

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