Doctrine:ORM Nightmare


The nightmare of the One-To-One Relation

Posted by Pedro Resende on 20/01/2015 03:20

This week, while working on a project, I've decided the implement correctly the database relations directly in the entity classes.

After designing the database model in MySQL Workbench, I've decided to define the association Mapping as described in the documentation.

It was a simple One-To-One, Unidirectional relation between two tables and I've used like it was supposed to.

The first table was Page and the second one, Language.

<?php
/** @Entity **/
class Product
{
    // ...

    /**
     * @OneToOne(targetEntity="Shipping")
     * @JoinColumn(name="shipping_id", referencedColumnName="id")
     **/
    private $shipping;

    // ...
}

/** @Entity **/
class Shipping
{
    // ...
}

When I've created the integration tests everything worked smoothly, however each time I tried adding a second entry to the database everything went south with the following error appearing.

Error Code: 1062
Duplicate entry 'saldjsdjald' for key 'id_language'

After googling it and hammering my head against the desk a few times, I've figured that Doctrine/ORM in the case of One-To-One relation creates an UNIQUE index !!! Of course they forgot to mention that on the documentation.

Thanks for the two hours I've spend googling the problem.

Seem the way to overcome this problem is to define a One-To-Many relation, using

/**
* @ORM/OneToMany(targetEntity="Language")
**/

This way it will simply create and index with the type INDEX and not UNIQUE.