Symfony2 Doctrine entity: How to create table in controller?

狂风中的少年 提交于 2020-01-26 03:17:05

问题


I need some functionality for dynamic creation table in DB. Algorithm is: 1) register new user -> make record in DB (this is simple) 2) after registration create table like user_data_abcdef123456... where abcdef123456 - is random pregenerated hash. this table must created from (for example) existing default entity (user_data_) Entity:

Path\To\Entity\UserData:
    type: entity
    table: user_data_
....

in Controller do like this:

$doctrine = $this->getDoctrine();

/** @var AbstractSchemaManager $manager */
$manager = $doctrine->getConnection()->getSchemaManager();
/** @var ClassMetadata $metadata */
$metadata = $doctrine->getManager()->getClassMetadata($class);
$metadata->setPrimaryTable(array('name' => $metadata->getTableName() . $project));

$table = new Table($metadata->getTableName());
$manager->createTable($table);

and I need set all column, all index.. etc.

Is there any correct solution?


回答1:


Hooray! I found solution! Thanks for trevorengstrom in Doctrine automatically create all the database tables answer. The solution is:

    $doctrine = $this->getDoctrine();

    /** @var ObjectManager|EntityManagerInterface $manager */
    $manager = $doctrine->getManager();

    /** @var ClassMetadata $metadata */
    $metadata = $manager->getClassMetadata($class);
    $metadata->setPrimaryTable(array('name' => $metadata->getTableName() . $project));

    $schemaTool = new SchemaTool($manager);
    $schemaTool->createSchema(array($metadata));  

where $class = 'DemoBundle:UserData' and $project = 'abcdef123456...';




回答2:


If you are using Repository (and you should use them) clean way of creating table:

class YourRepository extends EntityRepository
{
public function createTable()
{
    $schemaTool = new SchemaTool($this->getEntityManager());
    $schemaTool->createSchema(
        [$this->getClassMetadata()]
    );    
}

/**
* @param string $entityName Your entity full name like YourEntity::class
*/
public function createTableByEntity($entityName)
{
    $schemaTool = new SchemaTool($this->getEntityManager());
    $schemaTool->createSchema(
        [$this->getEntityManager()->getClassMetadata($entityName)]
    );    
}

}


来源:https://stackoverflow.com/questions/22818286/symfony2-doctrine-entity-how-to-create-table-in-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!