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

标签 mysql symfony doctrine

我正在尝试为我的 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/

相关文章:

mysql - 如何使用 NodeJS 的 SSH 隧道连接到 MYSQL 数据库?

php - mysql 查询 - 如何创建此查询?

javascript - 使用 jQuery 和 AJAX 提取 API 数据

php - 创建密码恢复表-插入值时出错

php - Doctrine 1.2 Pager - 它是否减少了从数据库请求的数据量

MYSQL 更改枚举值

php - 使用 phpMyAdmin 导出数据库时出现警告

php - 如何使用composer在Symfony2中安装phpdoc

php - symfony2 Doctrine ResultSetMapping 错误

php - 数据库:排序分层数据(修改后的预序树遍历):如何检索直系子级