Doctrine ORM default value of none existing entity

260 views Asked by At

Lets say we have entities which are named Element, those MAY belong to a entity called Layout. Elements and Layouts have a ManyToOne relation, where Many Elements belong to one Layout.

The databas engine used is MySQL, additionally we use a unique key, which the layout_id is a part of. So therefore we have in the Elements table, a column called layout_id which can not be null (because of the composite unique key), and has a default of 0. The value of 0 is a magic value and treated as 'No Layout assigned' throughout the code base (there are no FK's between Element and Layout because of this).

The problem with Doctrine ORM is that it tries to load a Layout with a ID of 0, which it can not find because it does not exists. We can not create a Layout entry with ID 0 because Layouts have other foreign keys and there own other constraints.

Is there any suggestion on how to overcome this. Basically when the layout_id in the Element is 0, we would like not to load a Layout.

1

There are 1 answers

0
Wilt On BEST ANSWER

In such case you cannot set this layout_id as part of the composite key. This is because of the foreign key constraint. Either your layout_id has to be nullable (meaning it cannot be part of the composite key) or you have to make a row in your layout table with id 0 (so it can be used as an identifier).

A solution could be to not use a composite key but instead add a primary key column for uniquely identifying your entity (surrogate key).