Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine optional OneToOne mapping

I'm trying to create a optional OneToOne mapping in Doctrine.

I have a table with all cities and zip codes available (this table shouldn't be changed), and I have a table with addresses and a mapped city. But sometimes I don't want to add City to my Address at the beginning (maybe later on it will). But when I don't add a City to the Address the persist on the Address gives me a Reflection Exception because there is no object like 'null' , which should be de City object.

I don't want to add an empty city every time into the database, because there should nothing be added or deleted to the city table.

Any suggestions? Or what am I missing?

class Address{
/**
 * @OneToOne(targetEntity="City")
 * @JoinColumn(name="city_id", referencedColumnName="id")
 */
  private $city = '';

Possible solutions I considered:

  • Create an empty city object in the db and assign this always to newly created Address objects (might cause a lot of overhead)
  • Create a ManyToMany relationship with an array of cities, so there can be zero or more cities added (I can restrict the multitude of cities in my Address object) but then I need a mapping table...
like image 556
jayv Avatar asked Jul 29 '11 07:07

jayv


1 Answers

Just simply add nullable=true to @JoinColumn annotation

like image 124
Maciej Pyszyński Avatar answered Sep 24 '22 23:09

Maciej Pyszyński