Symfony2 form and Doctrine OneToOne relationship

Go To StackoverFlow.com

0

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"
    }
2012-04-05 14:42
by Gianluca78


1

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.

2012-04-05 14:49
by Elnur Abdurrakhimov
I removed the avatarId field but I got the following error: Property avatarId does not exists in class Test\UserBundle\Entity\Use - Gianluca78 2012-04-05 14:55
You don't need it at all. The 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
Ah ok! I got it! Thank you - Gianluca78 2012-04-05 15:08


1

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).

2012-04-05 14:52
by Nick
Thank you, very useful - Gianluca78 2012-04-05 15:09
Ads