Moon soon
Moon soon

Reputation: 2856

How to disable FOREIGN KEY CONSTRAINT when using Doctrine generate migration?

I often change/add some field in Entity and using bin/console make:migration to generate migrations, that's convenience just like in Rails or Django. But I do not need Foreign Key Constraint when I am using Doctrine Relationships(ManyToOne, OneToMany...).

I have to delete lines contained Foreign Key Constraint in generated migrations. But When I doing some changes with Entity, and run bin/console make:migration, It will add Foreign Key Constraint again, it is annoying.

I do not care about data consistency.

In Django model ForeignKey you can set db_constraint=False, so migration would not generate Foreign Key constraint.

Is there some similar setting in Doctrine?

Upvotes: 6

Views: 7095

Answers (3)

D4V1D
D4V1D

Reputation: 5849

Why don't you just do the following?

$this->addSql('SET foreign_key_checks = 0');
// all SQL statements
$this->addSql('SET foreign_key_checks = 1');

This works.

Upvotes: 7

ste
ste

Reputation: 1529

Doctrine doesn't support this natively, but you can do that with an event listener on postGenerateSchema event.

// src/Doctrine/IgnoreFksListener.php

namespace App\Doctrine;

use Doctrine\ORM\Tools\Event\GenerateSchemaEventArgs;

/**
 * see http://kamiladryjanek.com/en/ignore-entity-or-table-when-running-doctrine2-schema-update-command/
 */
class IgnoreFksListener
{

    /**
     * Remove fks from Schema
     * This listener is called when the schema has been generated (from mapping data of entities)
     *
     * @param GenerateSchemaEventArgs $args
     */
    public function postGenerateSchema(GenerateSchemaEventArgs $args)
    {
        $schema = $args->getSchema();
        $em = $args->getEntityManager();

        foreach ($schema->getTables() as $table) {
            $fks = $table->getForeignKeys();
            foreach ($fks as $fk) {
                $table->removeForeignKey($fk->getName());
//              dump('removed FK '.$fk->getName().' from '.$tabel->getName().' pointing to '.$fk->getForeignTableName().'.['.implode(', ', $fk->getForeignColumns()).']');
            }
        }
    }
}

And you have to register the listener in services.yaml

    App\Doctrine\IgnoreFksListener:
        tags:
            - {name: doctrine.event_listener, event: postGenerateSchema }

here you can find another example http://kamiladryjanek.com/en/ignore-entity-or-table-when-running-doctrine2-schema-update-command/

Upvotes: 5

yivi
yivi

Reputation: 47300

Doctrine does not support this.

If you are using a relational back-end and declare association mappings between your entities, the generated code will include the appropriate foreign keys.

You are not required to use that code. If the FKs does not exist Doctrine will continue working fine, as you've discovered.

I do not care about data consistency

Oh, to be young and care-fee. Good luck with that.

Upvotes: 0

Related Questions