Search code examples
doctrine-ormannotationsentitynullableeager-loading

Doctrine2 - Annotations: eager load (join) vs. nullable column (ManyToOne)


I have this:

/**
 * @ManyToOne(targetEntity="TblCity",fetch="EAGER",cascade={"persist"})
 * @JoinColumn(name="tblCity",referencedColumnName="Id")
 */

and it creates the correct JOIN for table tblCity in sql and TblCity entity is plugged in my parent entity - aka "Eager-Load"

Pseudo result:

PersonEntity: {
    Id: 1
    ...
    CityEntity: {
        Id: 1
        ...
    }
}

but, this column NEEDS to be nullable

(if it runs into a "missing" foreign id it complains about missing proxy files for TblCity).

So it has to look like this:

/**
 * @Column(nullable=true)
 * @ManyToOne(targetEntity="TblCity",fetch="EAGER",cascade={"persist"})
 * @JoinColumn(name="tblCity",referencedColumnName="Id")
 */

and poff there goes the "Eager-Load"

The generated sql is missing the JOIN of table tblCity and the column contains only the id and not the entity for TblCity

Pseudo result:

PersonEntity: {
    Id: 1
    ...
    CityEntity: 1 (as integer)
}

What am I doing wrong?

PS: I CAN'T use createQuery or such things, so please no solutions involving that


Solution

  • The doctrine @JoinColumn annotation has an optiobal attribute nullable which defaults to true. Read more on this here in the documentation: 21.2.15. @JoinColumn

    So the proper way to declare nullable for the join column is:

    @JoinColumn(name="tblCity",referencedColumnName="Id", nullable=true)
    

    But nullable is true by default so you don't really need it...

    My guess would be that your @Column annotation is overruling the whole @ManyToOne annotation in your case. That is why you get only an id and no TblCity entity.