需要帮助理解一对一的Doctrine

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

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

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.