tags:

views:

51

answers:

2

i am actually reading Doctrine Reference: One to Many, Unidirectional with Join table. but this will probably be more of a SQL quesiton. basically, this is supposed to model a one to many, unidirectional relationship. i guess from the PHP code (in that link), its such that 1 user have many phonenumbers.

the question is from the SQL, it seems like 1 user can have many phonenumbers. and 1 phonenumber can only belong to 1 user. am i right?

CREATE TABLE User (
    id INT AUTO_INCREMENT NOT NULL,
    PRIMARY KEY(id)
) ENGINE = InnoDB;

CREATE TABLE users_phonenumbers (
    user_id INT NOT NULL,
    phonenumber_id INT NOT NULL,
    UNIQUE INDEX users_phonenumbers_phonenumber_id_uniq (phonenumber_id),
    PRIMARY KEY(user_id, 
phonenumber_id)
) ENGINE = InnoDB;

CREATE TABLE Phonenumber (
    id INT AUTO_INCREMENT NOT NULL,
    PRIMARY KEY(id)
) ENGINE = InnoDB;

ALTER TABLE users_phonenumbers ADD FOREIGN KEY (user_id) REFERENCES User(id);
ALTER TABLE users_phonenumbers ADD FOREIGN KEY (phonenumber_id) REFERENCES Phonenumber(id);

can't i just simplify the database to ... below ... no need for join tables and what not?

Users (id, name)
Phonenumbers (id, user [FK], number)
+3  A: 

Correct, these are two valid approaches to the same problem. And yes, the unique index on users_phonenumbers means that each phone number can belong to only one user.

David M
A timely answer there, David M. I was just about to post an answer that was completely wrong.
Brian Hooper
it seems the simple approach is what is used when i am doing a [one to many **BiDirectional**](http://www.doctrine-project.org/projects/orm/2.0/docs/reference/association-mapping/en#one-to-many,-bidirectional) but why the difference?
jiewmeng
A: 

The design is actually suboptimal.

The idea must have been that there are telephone numbers, users, and that they can be linked many-to-many. Because of the unique index on phonenumberid hoever, each number can only be assigned to one user.

Then the whole users_phonenumbers has become redundant, because they could just have added a userid column on the phonenumbers table and save themselves a join.

BAd table design if you ask me.

gjvdkamp
Sorry, forgot to read your last line. Yes, the join is redundant and you could simplify the design as you suggest.
gjvdkamp
@David M has it correct: both approaches are valid. The one you think is "BAd" is based on the worthy principle that a table is either an entity table or a relationship table but never both. It's a merely question of style, nothing more. In the context you use it, the term "suboptimal" is subjective (unless you care to post a proof...?)
onedaywhen