Reputation: 11
I'm updating the entity User which has a OneToMany bidirectional relationship with Profiles and a OneToOne relationship with Contact. When I update (flush) the User entity, everything is updated apart from the user column on tblProfile even though the entity returned is correct.
I've tried updating the User/Profile relationship from both sides, see the final 2 lines of the code snippet. Both methods return the correct final entities, however the table tblProfile isn't updated.
Any help is greatly appreciated, I can provide more parts of the code also!
/**
* @ORM\Entity(repositoryClass="App\Domain\Repository\ProfileRepository")
* @ORM\Table(name="tblProfile")
*/
class ProfileEntity
{
/**
* @ORM\ManyToOne(targetEntity="UserEntity", inversedBy="profiles")
* @ORM\JoinColumn(name="PfUScId", referencedColumnName="UScId")
*/
private ?UserEntity $user = null;
/**
* @return UserEntity|null
*/
public function getUser(): ?UserEntity
{
return $this->user;
}
/**
* @param UserEntity|null $user
*
* @return self
*/
public function setUser(?UserEntity $user): self
{
$this->user = $user;
return $this;
}
}
/**
* @ORM\Entity(repositoryClass="App\Domain\Repository\UserRepository")
* @ORM\Table(name="tblUser")
*/
class UserEntity
{
/**
* @var Collection
*
* @ORM\OneToMany(targetEntity="ProfileEntity", mappedBy="user")
*/
private Collection $profiles;
/**
* @param array $profiles
*
* @return self
*/
public function setProfiles(array $profiles): self
{
$this->profiles = new ArrayCollection();
foreach ($profiles as $profile) {
$this->profiles->add($profile);
}
return $this;
}
/**
* @return Collection
*/
public function getProfiles(): Collection
{
return $this->profiles;
}
}
class UserService
{
public function updateUser(
int $legacyUserId,
string $email,
): UserEntity {
$user = $this->userRepository->findOneBy(['legacyUserId' => $legacyUserId]);
$profiles = $user->getProfiles();
$existingContact = $this->checkContact($user, $email);
$Contact = $existingContact
? $existingContact :
$this->contactService->createContact($email);
$user->setContact($contact)->setId($contact->getId());
$updatedProfiles = [];
foreach ($profiles as $profile) {
$updatedProfiles[] = $profile->setContact($contact)->setUser($user);
}
$user->setProfiles($updatedProfiles);
$user = $this->userRepository->updateUser($user);
foreach($updatedProfiles as $profile) {
$this->profileService->changeUser($profile, $user);
}
return $user;
}
}
Upvotes: 1
Views: 500
Reputation: 2689
You would like to update profiles witch are already assigned to user, the profile has the id of user so you don't have to say $user->setProfiles($updatedProfiles);
because you will update just the profiles witch already exist.
try this :
// delete this line $updatedProfiles = [];
foreach ($profiles as $profile) {
// $updatedProfiles[] = to be deleted
$profile->setContact($contact)->setUser($user);
}
// delete this lline $user->setProfiles($updatedProfiles);
Upvotes: 1