OneToOne mapping with doctrine

I use doctrine, User and City entities are OneToOne to each other, When I call user entity, first I want to check if that entity has a city or not, if has it, update it, if doesn’t have it, create a city entity for that user.

I have this hasser method in my User entity:

public function hasCity() {  
  return $this->city instanceof City;
}

Then in my script I have:

$user = $em->find(User.....);

if ($user->hasCity()) {
    $city = $user->getCity();
    $zip = $city->getZip();
} else {
    $city = new City;
    $city->setUser($user);
} 

But I still get Entity City not found error. I did a print debug and noticed it never goes to else clause even if it doesn’t have city so I get Entity City not found error. What wrong I did in my script above?

This one works niether:

$user = $em->find(User...);
$city = $user->getCity();
if ($city !== null) {

It always assumes User has a City and never goes to else clause. There is no such problem for other mappings than OneToOne.
I guess this should because that both entities are mapped by identifiers of each other (as they are one to one) rather than the owning side having a FK? Should be that the issue?

What is returning here? Can you post your code for getCity()?

Also, a bit of a different question, but do you have an extra table of cities and zip codes in your database?

Scott

it is just

public function getCity() {  
  return $this->city;
}

But this does not matter, it never goes to else clause. city and user are OneToOne to each other and city is not mapped to any other entity. Any idea how to fix the issue?

Start by checking your database. Does your user table have a city id in it?

Most likely you have a mapping problem but the basics come first.

I might add the having a 1:1 relation between user and city seems a bit strange. Only one user per city?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.