Mirage
Mirage

Reputation: 31568

Is it possible to get the ID of entity after persist and before Flush in Doctrine2?

I have the User Login Registration Page.

Now on the same Page i have one more Forms i.e UserInterests.

Now i have the PostPersist function which creates new UserProfile after User is Persisted

Now UserProfile is linked with User ID and UserInterests is linked with UserProfile ID

Now the client wants UserInterests on same User page but i have problem that UserProfile is not yet created. Now how can persist them. Is there any way

Upvotes: 2

Views: 5841

Answers (1)

Asciiom
Asciiom

Reputation: 9975

I don't think you can get the ID before flushing.

You could create an association between the models, that way Doctrine will take care of the id's when saving and you can retrieve your UserInterests with something like:

$user->getProfile()->getInterests();

So you would have your User model with a property that holds your UserProfile:

/**
 * @OneToOne(targetEntity="UserProfile")
 * @JoinColumn(name="profile_id", referencedColumnName="id")
 **/
private $profile;

and your UserProfile class should have a property to hold the UserInterests model.

/**
 * @OneToOne(targetEntity="UserInterests")
 * @JoinColumn(name="interests_id", referencedColumnName="id")
 **/
private $interests;

You can now create an empty $userProfile model (to link the others together, the actual filling can be done in your postPersist function) and a $userInterests model, associate them by

$interests = new UserInterests();

// create an empty UserProfile, and fill it in your PostPersist function, 
// that way it can already be used to link the User and UserInterests
$profile = new UserProfile();

$profile->setInterests($interests);
$user->setProfile($profile);

Now Doctrine will fill in the ids when persisting and you don't need to worry about them.

More information here

Upvotes: 4

Related Questions