Doctrine - How to Establish a One-To-One Relationship Between Two Objects
I have two tables: users and contacts
Users
- ID
- Username
Contacts
- ID
- user_id
- email (I've simplified the structure)
Now, how to set up doctrine objects correctly?
/**
* @ORM\Entity
* @ORM\Table(name="users")
*/
class User extends BaseEntity {
/**
* @Id
* @GeneratedValue
* @Column(type="bigint")
*/
protected $id;
/**
* @ORM\Column(type="string", unique=true)
*/
protected $username;
/**
* @ORM\OneToOne(targetEntity="Contact")
* @ORM\JoinColumn(name="id", referencedColumnName="user_id", onDelete="CASCADE")
**/
protected $contact;
}
The contact person:
/**
* @ORM\Entity
* @ORM\Table(name="contacts")
*/
class Contact extends BaseEntity {
/**
* @Id
* @GeneratedValue
* @Column(type="bigint")
*/
protected $id;
/**
* @var User
* @ORM\OneToOne(targetEntity="User")
* @ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $user;
/**
* @ORM\Column(type="string")
*/
protected $email;
}
The thing is, I'm not sure if the entity relationship is set correctly.
- I don't know how to install, uninstall
User
and then uninstallContact
, but not vice versa. - If I create
$user = new User()
, then$contact = new Contact()
how to join them?$user->contact = $contact
? Will it be afterpersist()
andflush()
fill inuser_id
correctly and insert data into both tables? - I am getting the error
A new entity was found through the relationship '...\User#contact' that was not configured to cascade persist operations for entity: ...\Contact@0000000015f3aa5e000000012cd799f5. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist this association in the mapping for example @ManyToOne(..,cascade={"persist"}). If you cannot find out which entity causes the problem implement '...\Contact#__toString()' to get a clue.
I am stuck with this which I think is related to my problem # 1 and so I cannot check # 2.
I've been going through the docs for hours, but I got stuck and I didn't find any real example to guide me ... Can anyone help me by showing me the correct configuration of these entities' relationships?
source to share
To cascade the deletion of a user so that his contact is also deleted, in the object, Contact
add onDelete="CASCADE"
to the
JoinColumn
annotation for the property $user
(this will only delete the contact if his user is deleted)
/**
* @var User
* @ORM\OneToOne(targetEntity="User")
* @ORM\JoinColumn(name="user_id", referencedColumnName="id", onDelete="CASCADE")
*/
private $user;
If you save the contact before adding it to the user, you shouldn't get any errors. If you want to add a new contact by simply assigning a new unassigned contact to the user, then you need to add cascade={"persist", "remove"}
to your User
entity
/**
* @ORM\OneToOne(targetEntity="Contact",cascade={"persist", "remove"})
* @ORM\JoinColumn(name="id", referencedColumnName="user_id")
**/
protected $contact;
source to share