Wojciech Jasiński
Wojciech Jasiński

Reputation: 1490

Many-to-Many, Unidirectional, Self-referencing association in Doctrine2

I would like to 'link' some objects. Imagine you have Person table with these records:

As you can see it is one the same person. I would like to have association that stores alternative persons. For example for Person with ID=1 and NAME=Barack Obama linkedPersons would look like this:

linkedPersons:
    Obama Barack
    Barack Hussein Obama
    (optionally with Barack Obama itself)

IMHO it should be Many-to-Many, Unidirectional, Self-referencing association but I have no idea how to implement such an association.

Upvotes: 2

Views: 1977

Answers (1)

Marius Balčytis
Marius Balčytis

Reputation: 2651

I think you could do simple ManyToMany unidirectional mapping. On relation just relate both users. This would make additional records in database (A -> B and B -> A), but I think it should work as you want.

<?php
/** @Entity */
class User
{
    /**
     * @ManyToMany(targetEntity="User")
     * @JoinTable(name="alternateUsers",
     *      joinColumns={@JoinColumn(name="user_id", referencedColumnName="id")},
     *      inverseJoinColumns={@JoinColumn(name="alternate_user_id", referencedColumnName="id")}
     *      )
     */
    private $alternateUsers;

    public function __construct() {
        $this->alternateUsers = new \Doctrine\Common\Collections\ArrayCollection();
    }

    public function addAlternateUser(User $user) {
        $this->alternateUsers[] = $user;
        $user->alternateUsers[] = $this;
    }
}

Upvotes: 3

Related Questions