Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get table name of entity class

Do you know how to get the table name from an Entity declaration in my controller class

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 

I now would like to get the table name of the User entity, how would i do this in my Symfony2 controller?

like image 298
Matt Avatar asked Nov 23 '11 14:11

Matt


People also ask

How to define table name in entity class?

The easiest way to set a custom SQL table name is to annotate the entity with @javax. persistence. Table and define its name parameter: @Entity @Table(name = "ARTICLES") public class Article { // ... }

What is @entity annotation in spring boot?

The @Entity annotation specifies that the class is an entity and is mapped to a database table. The @Table annotation specifies the name of the database table to be used for mapping.

How do you map entity and table?

In Spring Data JPA we can map an entity to a specific table by using @Table annotation where we can specify schema and name. But Spring Data JDBC uses a NamingStrategy to map an entity to a table name by converting the entities class name.

What is entity class in spring boot?

An entity is a lightweight persistence domain object. Typically, an entity represents a table in a relational database, and each entity instance corresponds to a row in that table. The primary programming artifact of an entity is the entity class, although entities can use helper classes.


2 Answers

From within a controller you would use:

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

Note that the getClassMetadata method returns a bunch of interesting info about the entity.

like image 153
Steven Mercatante Avatar answered Sep 18 '22 13:09

Steven Mercatante


I needed to find out the name of a mapping Table in a many-to-many relationship (using FOSUserBundle). Maybe this helps someone:

    $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']; 
like image 42
con Avatar answered Sep 18 '22 13:09

con