Symfony2 Doctrine entity: How to create table in c

2019-08-18 23:30发布

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?

2条回答
混吃等死
2楼-- · 2019-08-18 23:47

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)]
    );    
}

}
查看更多
SAY GOODBYE
3楼-- · 2019-08-18 23:51

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...';

查看更多
登录 后发表回答