我有这个User
实体
/**
* User Entity.
*
* @ORM\Entity
* @ORM\Table(name="user")
* @ORM\Entity(repositoryClass="Application\Repository\UserRepository")
* @ORM\HasLifecycleCallbacks()
* @ORM\EntityListeners({"Application\Listener\User"})
*/
class User extends Entity implements UserInterface, ProviderInterface
{
...
/**
* @var \Application\Entity\Organization
*
* @ORM\ManyToOne(targetEntity="Application\Entity\Organization")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="organization_id", referencedColumnName="organization_id")
* })
*/
protected $organization;
...
}
使用听众
namespace Application\Listener;
use Doctrine\ORM\Event\PreUpdateEventArgs;
class User
{
public function preUpdate(\Application\Entity\User $user, PreUpdateEventArgs $eventArgs)
{
if ($eventArgs->hasChangedField('organization')) {
$oldOrganization = $eventArgs->getOldValue('organization');
if ($oldOrganization) {
$oldOrganization->decreaseTotalMembers();
$eventArgs->getEntityManager()->persist($oldOrganization);
}
$newOrganization = $eventArgs->getNewValue('organization');
if ($newOrganization) {
$newOrganization->increaseTotalMembers();
$eventArgs->getEntityManager()->persist($newOrganization);
}
}
}
}
因此,正如您所看到的,每次用户更改组织时,我都希望减少旧组织中的成员数量并增加新组织。
所以,在我创建组织的控制器中,我有:
public function createAction(){
...
$this->getOrganizationService()->hydrateOrganization($organization, $data);
$user = $organization->getAuthor();
if (!$user->hasOrganization()) {
$user->setOrganization($organization);
$this->getUserService()->saveUser($user);
}
...
}
所以我希望在保存用户(persist + flush)时,组织总成员的增加也会被刷新,但不会发生。
您是否知道为什么会发生这种情况以及如何解决?