我有2个实体与onomanomany关联。第二个实体有2个lifecycleCallbacks:prePersist
和preRemove
,它们会更改第一个实体。 prePersist
工作正常,第一个实体正在内存中更改并保存在数据库中。 preRemove
仅更改内存中的实体,而不保存在数据库中。
配置:
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);
}
测试
// 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();