从Controller创建和填充数据库(Symfony 2,Doctrine)

时间:2013-09-19 20:29:54

标签: mysql symfony doctrine

我正在尝试为我的Symfony 2.2.3应用程序创建一个安装Bundle。 因此,我想删除/创建一个数据库(mysql),然后通过Controller Actions创建模式。

我的代码:

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

数据库:drop和database:创建工作正常(两个命令都返回0),但是创建模式然后失败。

但是,当我将前两个命令注释掉时,只会执行doctrine:schema:create(当然,如果删除了子句)并重新加载页面而不更改其他任何内容数据库模式将被正确创建。

谁能告诉我这是什么问题?

1 个答案:

答案 0 :(得分:1)

此代码有效(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'));
}