I have 2 entities: User
and Avatar
. Each user can choice one avatar from a list, so I think this is a One2One unidirectional relationship. The problem is that the field avatar_id
is always NULL
in the db when I save the form.
Let's see the code:
class User implements UserInterface
{
/**
* @var int $avatarId
*
* @ORM\Column(name="avatar_id", type="integer", nullable=true)
*/
private $avatarId;
/**
* @var Avatar
*
* @ORM\OneToOne(targetEntity="Avatar", cascade={"persist", "remove"})
*/
private $avatar;
}
When I var_dump
the user object before saving, the field avatarId
contains the Avatar
object but the id is not saved. What I'm doing wrong?
["avatarId":"Test\UserBundle\Entity\User":private]=>
object(Test\UserBundle\Entity\Avatar)#419 (5) {
["id":"Test\User\Bundle\Entity\Avatar":private]=>
int(3)
["imageName":"Test\UserBundle\Entity\Avatar":private]=>
string(14) "death-dark.jpg"
}
You don't need the avatarId
field, since the avatar
field will take care of it automatically. You can use the @JoinColumn
annotation to set the referencing column name explicitly.
avatar
field is what you need to work with. The avatar_id
column is taken care of automatically - Elnur Abdurrakhimov 2012-04-05 15:00
A few things:
ID columns are typically generated with the following annotations:
/**
* @ORM\Id @ORM\Column(type="integer")
* @ORM\GeneratedValue
*/
This tells the ORM to automatically generate a value when you create a new object, thus when you dump the object it will have a value before persisting.
And a note on your OneToOne relationship, if Avatars can be used by multiple people from that list, that would be a ManyToOne relationship (Many users to one avatar, one avatar to many users).