2011-11-23 31 views
35

Bạn có biết làm thế nào để có được tên bảng từ một tuyên bố Entity trong lớp điều khiển của tôiNhận tên bảng của lớp thực thể

Entity Lớp

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

bây giờ tôi muốn lấy tên bảng của Thực thể người dùng, làm thế nào tôi sẽ làm điều này trong bộ điều khiển Symfony2 của tôi?

Trả lời

80

Từ bên trong một bộ điều khiển bạn sẽ sử dụng:

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

Lưu ý rằng phương pháp getClassMetadata trả về một loạt các thông tin thú vị về các thực thể.

+1

Tên bảng tham gia như thế nào? Bạn có biết làm thế nào để có được điều đó? –

+5

Với php 5.5+ bạn có thể sử dụng lớp học được tích hợp trong lớp :: class. '' '$ tableName = $ em-> getClassMetadata (User :: class) -> getTableName();' '' –

0

Với Symfony 2.3 & thuyết 2 này làm việc cho tôi:

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

tôi cần phải tìm ra tên của một bảng ánh xạ trong một mối quan hệ nhiều-nhiều (sử dụng FOSUserBundle). Có thể điều này giúp ai đó:

$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']; 
Các vấn đề liên quan