更新数据库架构Doctrine时执行sql脚本

时间:2016-04-15 13:54:01

标签: sql symfony doctrine-orm

执行时是否可以附加(或执行)自定义sql查询:

app/console doctrine:schema:update --force

我有一个脚本可以创建我的所有视图,并希望每当我更新数据库架构时都会更新它们。

1 个答案:

答案 0 :(得分:5)

当然,您可以扩展UpdateSchemaCommand命令并将EntityManager注入defining the command as a service

命令:

// src/AppBundle/Command/CustomUpdateSchemaCommand.php
<?php

namespace AppBundle\Command;

use Doctrine\Bundle\DoctrineBundle\Command\Proxy\UpdateSchemaDoctrineCommand;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Command\Command;

class CustomUpdateSchemaCommand extends UpdateSchemaDoctrineCommand
{
    /** @var EntityManagerInterface */
    private $em;

    /**
     * @param EntityManagerInterface $em
     */
    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;

        parent::__construct();
    }

    /**
     * {@inheritDoc}
     */
    protected function configure()
    {
        parent::configure();
    }

    /**
     * {@inheritDoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeln('Hello world');
        $conn = $this->em->getConnection();
        $conn->exec(/* QUERY */);


        return parent::execute($input, $output);
    }
}

服务:

// app/config/services.yml
app.command.custom_schema_update_command:
    class: App\SportBundle\Command\CustomUpdateSchemaCommand
    arguments: ["@doctrine.orm.entity_manager"]
    tags:
        -  { name: console.command }

希望这有帮助。