paproch
paproch

Reputation: 3

Symfony OneToOne relation not getting data in user entity

I got 2 entities User and Profile. User class code:

/**
 * @var Profile
 *
 * @ORM\OneToOne(targetEntity="Profile", inversedBy="user")
 */
private $profile;

/**
 * @param Profile $profile
 * @return $this
 */
public function setProfile($profile)
{
    $this->profile = $profile;

    return $this;
}

/**
 * @return Profile
 */
public function getProfile()
{
    return $this->profile;
}

Profile class code:

/**
 * @var User
 *
 * @ORM\OneToOne(targetEntity="User", mappedBy="profile")
 * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
 */
private $user;

/**
 * @param User $user
 * @return $this
 */
public function setUser($user)
{
    $this->user = $user;

    return $this;
}

/**
 * @return User
 */
public function getUser()
{
    return $this->user;
}

Now in my database in Profile entity I've got user_id, and in User entity I've got profile_id, but when I'm adding profile in User entity profile_id is NULL. In Profile class user_id is ok, but in User profile_id is set as NULL, can someone help me?

Upvotes: 0

Views: 483

Answers (2)

revengeance
revengeance

Reputation: 891

As previous answerer said - you shouldn't be setting it on both sides. So decide in which side you want.

One to one relation is basically the same one to many relation, with the only difference that in "mapped" side the entry cannot be more than once.

You have 2 options there. Setting profile to user or setting user to profile.

1) If at start you create users and then create profiles - you should place setters/getters in profile side

2) If at start you create profiles and then users, you should place setters/getters in user side

You don't need mapped by / inversed by in oneToOne relation...

Check following working code example. (So we will place setters/getters in Profile entity side)

/**
 * One Profile has One User.
 * @ORM\OneToOne(targetEntity="User")
 * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
 */
private $user;

public function setUser(User $user)
{
   $this->user = $user;
}

public function getUser()
{
   return $this->user();
}

ps. In overall, i'm thinking you're trying to make some easy things difficult with this relation. Why not just creating one entity ? Why you need two with one to one relation here ?

Upvotes: 1

OK sure
OK sure

Reputation: 2646

You shouldn't be setting it on both sides - since the Profile has inversedBy it is the owning side - hence the result in your database.

Your getters and setters will still work fine - the JoinColumn on user_id annotation is taking care of the relationship and profile_id is not actually being specified anywhere and is superfluous in your DB.

Upvotes: 0

Related Questions