26

I'm using doctrine2 with a symfony2.1 project. I have an entity that has a few many to one relationships to other tables. The foreign key relationships for these many-to-one's have already been updated in the database, but every time I run migrations:diff or schema:update --dump-sql it adds the same update commands to add the foreign key relationships again. When I run schema:validate it says my mapping is out of sync with my database.

My application works fine, the relationships are working properly, and the schema in my database looks correct. Why is doctrine still trying to add these foreign keys?

Here's my code (for one of the problematic parameters):

In my "Ticket" entity I have:

/**
 * Authenticated User who scored the ticket. 
 *
 * @ORM\ManyToOne(targetEntity="CS\SecurityBundle\Entity\User")
 * @ORM\JoinColumn(name="scoring_user_id", referencedColumnName="id")
 */
protected $scoringUser;

I currently have it set up to be one-directional, so there is no inversedBy in the User entity.

This generates the following in my migrations or schema:update dump even though it's in the database already:

$this->addSql("ALTER TABLE tickets ADD CONSTRAINT FK_54469DF4BB0D9452 FOREIGN KEY (scoring_user_id) REFERENCES users (id)");

Any idea what I'm doing wrong here?

4

1 回答 1

13

Why is doctrine still trying to add these foreign keys?

The correct term here is "foreign key constraint". Without the constraint, the column in question is just a column. It's the constraint that enforces that the value of that column exists as a primary key in another table.

Why is doctrine still trying to add these foreign keys?

Because the database vendor/engine doesn't support foreign key constraints, but Doctrine fails to recognize that.

If I have to guess, you're using MySQL with the MyISAM engine. MyISAM doesn't support foreign key constraints. Unfortunately Doctrine isn't "smart" enough to see that. It sees that MySQL is used, therefor blindly assumes that foreign key constraints are supported.

My advise is to switch to the InnoDB engine, unless you have a good reason for using MyISAM.

ALTER TABLE table_name ENGINE=InnoDB;

Converting Tables from MyISAM to InnoDB

于 2014-02-27T07:34:17.307 回答