views:

55

answers:

2

Referencing doctrine reference - one to many unidirectional

class User
{
  // ...

  /**
   * @ManyToMany(targetEntity="Phonenumber")
   * @JoinTable(name="users_phonenumbers",
   *      joinColumns={@JoinColumn(name="user_id", referencedColumnName="id")},
   *      inverseJoinColumns={@JoinColumn(name="phonenumber_id", referencedColumnName="id", unique=true)}
   *      )
   */
  private $phonenumbers;

  // ...
}

The part I don't understand is unique=true. What does it do? The way I read it is ...

  • User has a Many to Many relationship with Phonenumber
  • it uses the join table users_phonenumbers
  • users_phonenumbers.user_id = users.id
  • users_phonenumbers.phonenumber_id = Phonenumber.id
  • and I guess the unique does something to constraints a many to many to a many to one relationship somehow. But how do you explain it? Also in a SQL sense (what is the output like)?
A: 

Hi Jacob,

The unique constraints ensure that data contained in a column or a group of columns is unique.

Be aware, two null values are NOT considered equal, so you can store two or more duplicate rows. The primary key is already unique, so you don't need to use for primary key columns. :)

P.

praethorian
in the context of the example, which columns will be unique?
jiewmeng
+1  A: 

The mapping translates into the following SQL tables (assuming both have a surrogate ID, called id):

CREATE TABLE User (id INT(10) PRIMARY KEY)
CREATE TABLE Phonenumber (id INT(10) PRIMARY KEY)
CREATE TABLE User_Phonenumber (
  user_id INT(10),
  phonenumber_id INT(10),
  PRIMARY KEY (user_id, phonenumber_id),
  UNIQUE(phonenumber_id)
);

What this means in terms of your code:

$phonenumber = new Phonenumber();
$phonenumber->setNumber("123-4567890");
$user1->addPhonenumber($phonenumber);
$user2->addPhonenumber($phonenumber);
$entityManager->flush();

This would throw a unique constraint exception, you cannot add the same phonenumber to different users, because phonenumbers are unique (on the database level).

beberlei
hmm wait, from the SQL, wont `phonenumber` be unique on the table `User_phonenumber` only? from the sql, i interprete as, 1 user can have many phonenumbers but 1 phonenumber can be for 1 user only cos its unique to the **table** not **database**?
jiewmeng
correct, that is what a One-To-Many is about. One User has Many Phonenumbers, Many Phonenumbers have One User.there can be only one phonenumber anyways, since the ID is a primary key, which is always unique.However you still could connect a unique phonenumber with many users, unless the phonenumber_id is also Unique on the Many-To-Many JoinTable.
beberlei