我正在尝试为我的 Symfony 2.2.3 应用程序创建安装包。 因此我想删除/创建一个数据库(mysql),然后通过 Controller 操作创建架构。
我的代码:
$kernel = $this->get('kernel');
$application = new \Symfony\Bundle\FrameworkBundle\Console\Application($kernel);
$application->setAutoExit(false);
// drop old database
$options = array('command' => 'doctrine:database:drop', '--force' => true);
$application->run(new \Symfony\Component\Console\Input\ArrayInput($options));
// create new database
$options = array('command' => 'doctrine:database:create');
$result = $application->run(new \Symfony\Component\Console\Input\ArrayInput($options));
// check if database:create was successful, then create schema
if($result == 0) {
$options = array('command' => 'doctrine:schema:create');
$result = $application->run(new \Symfony\Component\Console\Input\ArrayInput($options));
}
database:drop 和database:create 工作正常(两个命令都返回 0),但创建架构失败。
但是,当我注释掉前 2 个命令以便仅执行doctrine:schema:create(当然删除 if 子句)并重新加载页面时不更改任何其他内容数据库架构将正确创建。
谁能告诉我问题出在哪里?
最佳答案
此代码有效(Symfony 2.7)
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;
/**
* @Route("/resetDB", name="adminResetDB")
*/
public function resetDBAction()
{
$application = new Application($this->get('kernel'));
$application->setAutoExit(false);
// Drop old database
$options = array('command' => 'doctrine:database:drop', '--force' => true);
$application->run(new ArrayInput($options));
// Make sure we close the original connection because it lost the reference to the database
$this->getDoctrine()->getManager()->getConnection()->close();
// Create new database
$options = array('command' => 'doctrine:database:create');
$application->run(new ArrayInput($options));
// Update schema
$options = array('command' => 'doctrine:schema:update','--force' => true);
$application->run(new ArrayInput($options));
// Loading Fixtures, --append option prevent confirmation message
$options = array('command' => 'doctrine:fixtures:load','--append' => true);
$application->run(new ArrayInput($options));
return $this->redirect($this->generateUrl('index'));
}
关于mysql - 从 Controller 创建和填充数据库(Symfony 2,Doctrine),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18904352/