我有一个实体“组织”和一个实体“用户”都设置为ManyToMany,组织(组织)的领导者可以向其组织添加新用户,如果没有,将在数据库中创建用户已存在或链接到它(如果已存在)。
但是当领导者想要从组织中删除用户时,该用户将从数据库中删除,我不希望这种情况发生,因为用户可以不属于一个组织或属于多个组织而存在。
#[ORM\ManyToMany(targetEntity: User::class, mappedBy: 'organizations', cascade: ['persist'])]
private Collection $users;
/**
* @return Collection<int, User>
*/
public function getUsers(): Collection
{
return $this->users;
}
public function addUser(User $user): static
{
if (!$this->users->contains($user)) {
$this->users->add($user);
$user->addOrganization($this);
}
return $this;
}
public function removeUser(User $user): static
{
if ($this->users->removeElement($user)) {
$user->removeOrganization($this);
}
return $this;
}
#[ORM\ManyToMany(targetEntity: Organizations::class, inversedBy: 'users')]
private Collection $organizations;
/**
* @return Collection<int, organizations>
*/
public function getOrganizations(): Collection
{
return $this->organizations;
}
public function addOrganization(Organizations $organization): static
{
if (!$this->organizations->contains($organization)) {
$this->organizations->add($organization);
}
return $this;
}
public function removeOrganization(Organizations $organization): static
{
$this->organizations->removeElement($organization);
return $this;
}
我尝试使用 Doctrine 生成的不同函数,但我尝试的所有最终结果都是从数据库中删除用户。
这是我当前的代码:
class OrganizationUserRemovingProcessor implements ProcessorInterface
{
public function __construct(private OrganizationsRepository $organizationsRepository, private UserRepository $userRepository, private EntityManagerInterface $entityManager)
{
// dd('Bonjour!');
}
public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): mixed
{
$organization = $this->organizationsRepository->findOneBy(['id' => $uriVariables['id']]);
if ($organization) {
$user = $this->userRepository->findOneBy(['id' => $uriVariables['userId']]);
if ($user) {
$user->removeOrganization($organization);
$this->entityManager->flush();
return $organization;
}
}
return null;
}
}
您是否尝试在两个实体中都这样做?
<?php
class Organization
{
public function removeUser(User $user): static
{
if ($this->users->contains($user)) {
$this->users->removeElement($user);
$user->removeOrganisation($this);
}
}
}
class User
{
public function removeOrganization(Organizations $organization): static
{
if ($this->organisations->contains($organisation)) {
$this->organisations->removeElement($organisation);
$organisation->removeUser($this);
}
}
}