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?
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 { // ... }
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.
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.
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.
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.
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'];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With