如何使用doctrine迁移创建sql触发器?
这是迁移:
<?php
namespace App\Migrations;
use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\DBAL\Schema\Table;
/**
* Auto-generated Migration: Please modify to your needs!
*/
class Version20151211173441 extends AbstractMigration
{
/**
* @param Schema $schema
*/
public function up(Schema $schema)
{
$table = $schema->createTable('public.users');
$table->addColumn('id', 'integer', [
'autoincrement' => true
]);
$table->addColumn('name', 'string');
$table->setPrimaryKey(['id']);
$this->addSql("
CREATE OR REPLACE FUNCTION public.users_insert_trigger()
RETURNS TRIGGER AS $$
BEGIN
NEW.name := NEW.name || ' test';
RETURN NEW;
END;
$$
LANGUAGE plpgsql;
");
$this->addSql("
CREATE TRIGGER users_on_insert_trigger
BEFORE INSERT ON public.users
FOR EACH ROW EXECUTE PROCEDURE public.users_insert_trigger();
");
}
/**
* @param Schema $schema
*/
public function down(Schema $schema)
{
$this->addSql("DROP TRIGGER public.users_on_insert_trigger ON users");
$this->addSql("DROP FUNCTION public.users_insert_trigger()");
$schema->dropTable('users');
}
}
这会产生以下错误:
SQLSTATE [42P01]:未定义的表:7错误:关系&#34; public.users&#34; 不存在
并生成以下sql:
CREATE OR REPLACE FUNCTION public.users_insert_trigger()
RETURNS TRIGGER AS $$
BEGIN
NEW.name := NEW.name || ' test';
RETURN NEW;
END;
$$
LANGUAGE plpgsql;
CREATE TRIGGER users_on_insert_trigger
BEFORE INSERT ON public.users
FOR EACH ROW EXECUTE PROCEDURE public.users_insert_trigger();
CREATE TABLE public.users (id SERIAL NOT NULL, name VARCHAR(255) NOT NULL, PRIMARY KEY(id));
INSERT INTO common.migrations (version) VALUES ('20151211173441');
如果我正确理解,则在迁移结束时应用架构更改。 但它并不适合我......
那么,我该如何处理呢?
答案 0 :(得分:1)
您已正确总结了问题:迁移运行器实际执行您在使用模式生成SQL之前通过addSQL()添加的SQL。
您需要将此更改作为两个单独的迁移进行。
答案 1 :(得分:0)
所以你可以:
没有Schema,您的迁移看起来像这样
<?php
public function up(Schema $schema)
{
$platform = $this->connection->getSchemaManager()->getDatabasePlatform();
$table = new Table('table_name'/*, ...*/);
// ...
$sql = $platform->getCreateTableSQL($table);
// or
$sql = $platform->getDropTableSQL($table);
// etc.
$this->addSql($sql);
}