doumen6605 2016-01-03 15:42
浏览 66

无法在preRemove中更改和保存关联的实体

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();
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥30 Unity接入微信SDK 无法开启摄像头
    • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
    • ¥20 cad图纸,chx-3六轴码垛机器人
    • ¥15 移动摄像头专网需要解vlan
    • ¥20 access多表提取相同字段数据并合并
    • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
    • ¥20 Java-Oj-桌布的计算
    • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
    • ¥20 有人知道这种图怎么画吗?
    • ¥15 pyqt6如何引用qrc文件加载里面的的资源