克隆后,外键不会持久化symfony2

时间:2013-08-06 09:38:03

标签: symfony doctrine foreign-keys

我正在使用symfony + Doctrine而且我遇到了一个问题:
我克隆了一个现有的对象,我想改变克隆上的FK。它应该是这样的:

$dafCloned = clone $daf;
$dafState = $dafStateRepository->findOneBy(
        array(
            'name' => 'saved',
            'dafType' => 'invoice',
            'company' => $daf->getSeller(),
        ));
$dafCloned->setDafState($dafState);
var_dump($dafState->getId());
var_dump($dafCloned->getDafState()->getId());
$this->em->persist($dafCloned);
$this->em->flush();

你可能已经注意到了,我在这里得到了2个var_dump。以下是调用此代码的Custom Command的打印:

int(5500)
int(5499)

5500是db中$ dafCloned应该有的id,5499是$ daf的id。
我想知道为什么我有不同的身份......我的dafState应该是一样的。我可能错过了一些非常愚蠢的东西,但我从上午9点开始就坚持使用它...我甚至试图删除我们拥有的所有缓存,移动flush()persist()但是无法帮助:s

编辑:如果需要,添加setDafState()方法,但这是基本的:

public function setDafState(DafState $dafState) {

    $this->dafState = $dafState;

    return $this;
}

EDIT2: 这里是getDafState():

/**
 * Get dafState
 *
 * @return MyPath\Entity\DafState
 */
public function getDafState() {
    return $this->dafState;
}

如果您需要更多代码示例,只需要它,我会编辑;)

对于对象,两者都是巨大的(Doctrine对象),我找不到任何方法来获得有用的东西:s。我不能在$ daf对象上使用grep dafState,输出仍然很大。

编辑3:

if ($daf->getId() == 8902) // daf test which should be duplicated
                var_dump($dafCloned->getDafState() === $dafState);

输出

bool(true)

2 个答案:

答案 0 :(得分:0)

$dafCloned = clone $daf; // Here your clone is the same object as the old one
$dafState = $dafStateRepository->findOneBy( // Here you get some fresh object
                array(
                        'name' => 'saved',
                        'dafType' => 'invoice',
                        'company' => $daf->getSeller(),
                ));
$dafCloned->setDafState($dafState); // Because this object is still managed by the entity manager it will set the $dafState on the old object (tracked by Id most likely)
var_dump($dafState->getId()); // Show the Id on the fresh object
var_dump($dafCloned->getDafState()->getId()); // Show the Id on the old object
$this->em->persist($dafCloned); // overwrite the old object
$this->em->flush();

这篇文章对您有所帮助:How to re-save the entity as another row in Doctrine 2 如果这不能解决您的问题,我会更新我的答案

答案 1 :(得分:0)

我们走了。

感谢@cheesemacfly,我发现我有一个prePersistListener正在重置我的dafState!

所以,下次你有一些奇怪的东西看起来像上面的问题,检查你的听众!