【问题标题】:Is there an Event listener for Doctrine 2 Create Schema?Doctrine 2 Create Schema 是否有事件侦听器?
【发布时间】:2013-01-09 20:39:54
【问题描述】:

我想在 Doctrine Create Schema Event 上向数据库中插入一些记录(一些用于外键约束的默认数据)。

这个函数是通过命令行(在 Symfony2 中)通过触发来调用的:

php app/console doctrine:schema:update --force

运行此命令时,Doctrine2 会为数据库生成架构。

有没有办法对此做出反应并将数据插入数据库?

谢谢!

【问题讨论】:

  • 否,但您可以创建自己的命令:完成架构更新并一次性添加记录。
  • DoctrineFixtureBundle!它将帮助您加载初始数据。
  • @GreenLeaf,你能把它添加为答案吗?谢谢!

标签: php symfony doctrine doctrine-orm


【解决方案1】:

创建一个新的Console Command 将完成您的任务。

命令代码

MyCool/Bundle/Command/GenerateSchemaUpdateCommand.php

<?php
namespace MyCool\Bundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class GenerateSchemaUpdateCommand extends ContainerAwareCommand
{
    /**
     * Configure command, set parameters definition and help.
     */
    protected function configure()
    {
        $this
            ->setName('mycoolbundle:schema:update')
            ->setDescription('Perform my custom schema update.')
            ->setHelp(sprintf(
            'Performs the doctrine:schema:update plus adds our custom records. \n' .
                PHP_EOL
        ));
    }

    /**
     * Execution Code
     * @param \Symfony\Component\Console\Input\InputInterface $input
     * @param \Symfony\Component\Console\Output\OutputInterface $output
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $output = system('php -f app/console doctrine:schema:update --force');
        // do your custom things here.
        echo $output;
    }
}

执行你的命令

php -f app/console mycoolbundle:schema:update

添加参数

您可以使用以下方法为命令添加参数:

addArgument('var_name', InputArgument::OPTIONAL, 'Help message...')
// InputArgument::REQUIRED is also available here

备注

通过这种方式,您可以为控制台命令添加大量功能,此外,如果您选择需要它们,您还可以直接访问模型和实体。

【讨论】:

    【解决方案2】:

    DoctrineFixtureBundle

    它将帮助您加载初始数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-04
      • 2018-10-11
      • 2018-03-24
      • 2012-10-23
      • 2017-09-14
      • 1970-01-01
      • 2022-01-10
      相关资源
      最近更新 更多