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
avatarIdfield, since theavatarfield will take care of it automatically. You can use the@JoinColumnannotation to set the referencing column name explicitly.