ORM UniqueConstraint, null value duplicate

你离开我真会死。 提交于 2019-12-05 15:02:40

Am also faced the same issue, didn't find any way to resolve it.

Finally added one more varchar column to my table, its value is combination of 3 fields. ex:5_1_0(manually checking and adding 0 for null constraint otherwise constraint Id) and added unique constraint on new column and removed existing constraint.

This could be achieved using two partial indexes. But doctrine annotations is not enough. We should add some SQL to solve the issue.

NOTE! I'm using PostgreSQL and migrations in my project.

First create 2 unique indexes (I use YAML):

uniqueConstraints:
    table_idx_2_fields:
        columns: [ field1, field2 ]
    table_idx_3_fields:
        columns: [ field1, field2, field3 ]

Then generate migration class using console:

php app/console doctrine:migrations:diff

SQL will be generated, but must be modified a little bit (WHERE clauses added)

class Version20170622165834 extends AbstractMigration
{
    /**
     * @param Schema $schema
     */
    public function up(Schema $schema)
    {
        // ...

        $this->addSql('
            CREATE UNIQUE INDEX table_idx_2_fields ON tbl (field1, field2)
            WHERE field3 IS NULL;
        ');
        $this->addSql('
            CREATE UNIQUE INDEX table_idx_3_fields ON tbl (field1, field2, field3)
            WHERE field3 IS NOT NULL;
        ');
    }

    /**
     * @param Schema $schema
     */
    public function down(Schema $schema)
    {
        // ...
    }
}

Execute generated SQL (migrate):

php app/console doctrine:migrations:migrate -n

Done!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!