1
votes

I have two entities. User and Contact. User and contact have the same property phone_number. I would like to get all contacts with user object if its exists. It is also possible that the same phone number exists in contact table but it doesn't exist in user table.

Below is an annotation in contact entity:

/**
 * @ORM\OneToOne(targetEntity="Dlabs\ServiceBundle\Entity\User", mappedBy="contact")
 * @ORM\JoinColumn(name="phone", referencedColumnName="phone_number", nullable=true)
 */
private $user;

When I update my schema I get below errors:

[Doctrine\DBAL\DBALException] An exception occurred while executing 'ALTER TABLE contact ADD CONSTRAINT FK_83DFDFA4444F97DD FOREIGN KEY (phone) REFERENCES users (phone_number) NOT DEFERRABLE INITIALLY IMMEDIATE': SQLSTATE[23503]: Foreign key violation: 7 ERROR: insert or update on table "contact" violates foreign key constraint "fk_83dfdfa4444f97dd" DETAIL: Key (phone)=(+38640775xxx) is not present in table "users".

[PDOException] SQLSTATE[23503]: Foreign key violation: 7 ERROR: insert or update on table "contact" violates foreign key constraint "fk_83dfdfa4444f97dd" DETAIL: Key (phone)=(+38640775xxx) is not present in table "users".

Does anyone know in which way I should change my annotations so this will work? Thanks!

1

1 Answers

2
votes

There's no change you can make to your annotations to make this work with your existing relationships.

You have defined a nullable one-to-one relationship between the Contact and User entities. From a class perspective this means that a Contact's $user must either point to an instance of User or be null. From the corresponding table perspective this means that contact.phone must match a user.phone_number or be null.

Whilst in PHP loose typing means it is theoretically possible for a Contact's $user to be either a User object or a string phone number, this cannot be represented with doctrine mapping.

Two possible alternatives are:

  1. Don't define an explicit entity relationship between Contact and User but make use of queries to link them together (you could put the queries into a custom ContactRepository).

  2. Create a third entity, PhoneNumber which maps to a separate table. Then Contact would have a one-to-one relationship with a PhoneNumber ($phone) and PhoneNumber would have a one-to-one relationship with a User (e.g. $owner). Then the phone number belonging to a contact can exist regardless of whether it has an associated User.