I have 2 entities with association onetomany. 2-nd entity has 2 lifecycleCallbacks: prePersist
and preRemove
, that change 1-st entity. prePersist
works fine, 1-st entity is changing in memory and is saving in DB. preRemove
only changes entity in memory, without saving in DB.
Config:
ORM\Entity\TestUser:
type: entity
table: test_user
fields:
friendCount:
type: integer
column: friend_count
friendReverseCount:
type: integer
column: friend_reverse_count
...
oneToMany:
friends:
targetEntity: ORM\Entity\TestUserFriend
cascade:
- persist
- remove
fetch: LAZY
mappedBy: user
orphanRemoval: true
friendsReverse:
targetEntity: ORM\Entity\TestUserFriend
cascade:
- persist
- remove
fetch: LAZY
mappedBy: friend
orphanRemoval: true
ORM\Entity\TestUserFriend:
type: entity
table: test_user_friend
...
manyToOne:
user:
targetEntity: ORM\Entity\TestUser
cascade: {}
fetch: EAGER
inversedBy: friends
joinColumns:
user_id:
referencedColumnName: id
friend:
targetEntity: ORM\Entity\TestUser
cascade: {}
fetch: EAGER
inversedBy: friendsReverse
joinColumns:
friend_id:
referencedColumnName: id
lifecycleCallbacks:
prePersist: [prePersist]
preRemove: [preRemove]
ORM\Entity\TestUserFriend lifecycleCallbacks
public function prePersist($event)
{
$this->getUser()->setFriendCount($this->getUser()->getFriendCount()+1);
$this->getFriend()->setFriendReverseCount($this->getFriend()->getFriendReverseCount()+1);
}
public function preRemove($event)
{
$this->getUser()->setFriendCount($this->getUser()->getFriendCount()-1);
$this->getFriend()->setFriendReverseCount($this->getFriend()->getFriendReverseCount()-1);
}
tests
// works (friend_count increments in DB)
$userFriend = new \ORM\Entity\TestUserFriend();
$userFriend->setUser($user);
$userFriend->setFriend($friend);
$user->getFriends()->add($userFriend);
$em->persist($user);
$em->flush();
// don't work (friend_count without changes in DB)
$user->getFriends()->removeElement($user->getFriends()->current());
$em->persist($user);
$em->flush();