Last Updated: February 25, 2016
· lele19871

PHP DoctrineORM and empty FK values

I'm starting this tip saying "use empty strings in foreign key values instead of null is just WRONG".

But... sometimes you have to use historical (or prehistoric if you prefer) databases, and they maybe store empty strings (or 0 number) and not expected NULL in fk columns... and maybe you cannot change this behavior... so what to do? You are going to get a lot of EntityNotFoundException...

You can change doctrine's behavior by editing the createEntity method in UnitOfWork class.

Here's how:

foreach ($assoc['targetToSourceKeyColumns'] as $targetColumn => $srcColumn) {
                       $joinColumnValue = isset($data[$srcColumn]) ? $data[$srcColumn] : null;

                       // START-EDIT

                       // GT: our moas store empty string instead of null in fk columns.
                       // So, let's check and handle it as null!

                       if (empty($joinColumnValue))
                           $joinColumnValue = null;

                       // END-EDIT

                       if ($joinColumnValue !== null) {
                           if ($targetClass->containsForeignIdentifier) {
                               $associatedId[$targetClass->getFieldForColumn($targetColumn)] = $joinColumnValue;
                           } else {
                               $associatedId[$targetClass->fieldNames[$targetColumn]] = $joinColumnValue;