我想在用户注册时为其创建数据库。数据库创建的代码如下所示
$connectionFactory = $this->container->get('doctrine.dbal.connection_factory');
$connection = $connectionFactory->createConnection(array(
'driver' => 'pdo_mysql',
'user' => 'root',
'password' => 'mysecretpassword',
'host' => 'localhost',
'dbname' => 'userdatabase',
));
$params = $connection->getParams();
$name = isset($params['path']) ? $params['path'] : $params['dbname'];
unset($params['dbname']);
$tmpConnection = DriverManager::getConnection($params);
// Only quote if we don't have a path
if (!isset($params['path'])) {
$name = $tmpConnection->getDatabasePlatform()->quoteSingleIdentifier($name);
}
$error = false;
try {
$tmpConnection->getSchemaManager()->createDatabase($name);
echo sprintf('<info>Created database for connection named <comment>%s</comment></info>', $name);
} catch (\Exception $e) {
echo sprintf('<error>Could not create database for connection named <comment>%s</comment></error>', $name);
echo sprintf('<error>%s</error>', $e->getMessage());
$error = true;
}
$tmpConnection->close();
我在AccountBundle中为该数据库创建了实体,但在创建用户数据库时却不知道如何创建数据库模式。
答案 0 :(得分:1)
它经常用于测试中。在LiipFunctionalTestBundle中可以看到一个例子。
$metadatas = $om->getMetadataFactory()->getAllMetadata();
$schemaTool = new SchemaTool($om);
$schemaTool->dropDatabase($name);
if (!empty($metadatas)) {
$schemaTool->createSchema($metadatas);
}