1

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

我的代码:

$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 个命令注释掉以便仅执行教义:架构:创建(当然,如果删除了子句)并重新加载页面而不更改任何其他内容时,将正确创建数据库架构。

谁能告诉我问题是什么?

4

1 回答 1

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'));
}
于 2015-01-09T23:22:01.210 回答