Andreas Linden
Andreas Linden

Reputation: 12721

Doctrine 2 entity association does not set value for foreign key

I'm encountering a problem with a Doctrine 2 entity association. I have a User entity and an Agency entity. One Agency can employ multiple Users (the entities are simplified to show only my problem)

User Entity

/**
 * @Entity
 * @Table(name="users")
 **/
class User
{
    /**
     * @Id
     * @Column(type="integer")
     * @GeneratedValue
     * @var integer
     **/
    protected $id;

    /**
     * @ManyToOne(targetEntity="Agency", inversedBy="users"})
     * @JoinColumn(name="agency_id", referencedColumnName="id")
     * @var Agency
     */
    protected $agency;
}

Agency Entity

/**
 * @Entity
 * @Table(name="agencies")
 **/
class Agency
{
    /**
     * @Id
     * @Column(type="integer")
     * @GeneratedValue
     * @var integer
     **/
    protected $id;

    /**
     * @OneToMany(targetEntity="User", mappedBy="agency", cascade={"all"})
     * @JoinColumn(name="id", referencedColumnName="agency_id")
     * @var User[]
     */
    protected $users;


    /**
     * Add a user to the agency
     *
     * @param User $user
     * @return void
     */
    public function addUser(User $user) {

        $this->users[] = $user;
    }
}

When I now use the following code to create an agency along with a user, Doctrine does not set the agency_id for the user which results in a mysql contraint error that the user's agency_id must not be null.

// $em is the Doctrine EntityManager
$agency = new Agency;
$user = new User;
$agency->addUser($user);
$em->persist($agency);
$em->flush();

so far, the only way I found to make Doctrine set the agency_id for the user is assigning the agency to the user additionally to adding the user to the agency. In my understanding of an ORM it should already set the agency_id when the user is in the users collection of teh agency and it's beeing saved.

$user->agency = $agency;
$agency->addUser($user);

Is there anything wrong or missing with my annotations/metadata?

Upvotes: 2

Views: 1642

Answers (1)

Andreas Linden
Andreas Linden

Reputation: 12721

I found something in the Doctrine 2 documentation:

Changes made only to the inverse side of an association are ignored. Make sure to update both sides of a bidirectional association (or at least the owning side, from Doctrine’s point of view)

As in my case the owning side is the User I must update it. Doctrine 1 was able to manage it automatically... too bad.

Upvotes: 1

Related Questions