Symfony 没有找到最近持久的实体 - Doctrine/Symfony



我正在尝试做一个简单的操作:创建 2 个条目; 在每次创建时,首先检查实体是否存在,创建它,如果不存在,然后进行调整。在某些情况下(在第一次此类操作中(,我们需要在第一个条目中创建实体,并在第二个条目中使用它。不幸的是,这不会发生,我们最终会得到两个无用的条目。在此初始问题之后,一切都按预期工作(即在下一次迭代中正确找到实体(。

以下是条目的代码:

// Create first entry
$debitCode = 'bank';
$creditCode = 'equity';
// Create entry
$accountEntry = new AccountEntry();
$accountEntry->setAmount($amount);
$debitAccount = $unit->getAccountByType($debitCode);
if (!$debitAccount) {
// Create debit account
$debitAccountType = $em->getRepository('App:AccountType')->findOneBy(['code' => $debitCode]);
$debitAccount = new Account();
$debitAccount->setType($debitAccountType);
$em->persist($debitAccount);
}
$debitAccount->debit($amount);
$accountEntry->setDebitAccount($debitAccount);
$creditAccount = $unit->getAccountByType($creditCode);
if (!$creditAccount) {
// Create credit account
$creditAccountType = $em->getRepository('App:AccountType')->findOneBy(['code' => $creditCode]);
$creditAccount = new Account();
$creditAccount->setType($creditAccountType);
$em->persist($creditAccount);
}
$creditAccount->credit($amount);
$accountEntry->setCreditAccount($creditAccount);
$em->persist($accountEntry);
$em->flush();

// Create second entry
$debitCode2 = 'accountsPayable';
$creditCode2 = 'bank';
$accountEntry2 = new AccountEntry();
$accountEntry2->setAmount($amount);
$debitAccount = $unit->getAccountByType($debitCode2);
if (!$debitAccount) {
// Create debit account
$debitAccountType = $em->getRepository('App:AccountType')->findOneBy(['code' => $debitCode2]);
$debitAccount = new Account();
$debitAccount->setUnit($unit);
$debitAccount->setType($debitAccountType);
$em->persist($debitAccount);
}
$debitAccount->debit($amount);
$accountEntry2->setDebitAccount($debitAccount);
$creditAccount = $unit->getAccountByType($creditCode2);
if (!$creditAccount) {
// Create credit account
$creditAccountType = $em->getRepository('App:AccountType')->findOneBy(['code' => $creditCode2]);
$creditAccount = new Account();
$creditAccount->setUnit($unit);
$creditAccount->setType($creditAccountType);
$em->persist($creditAccount);
}
$creditAccount->credit($amount);
$accountEntry2->setCreditAccount($creditAccount);
$em->persist($accountEntry2);
$em->flush;

下面是getAccountByType函数:

/**
* Get Account by type of account.
*/
public function getAccountByType($code)
{
$filter = function ($account) use ($code) {
if ($account->getType()->getCode() == $code) {
return $account;
}
};
$accounts = $this->accounts->filter($filter)->getValues();
return isset($accounts[0]) ? $accounts[0] : null;
}

当然,在我发布问题 30 分钟后,我自己找到了答案(尽管在发布前几天一直在用头撞墙(。

基本上,我们需要在持久/刷新初始条目后刷新$unit实体:

$em->refresh($unit);

否则,getAccountByType 方法显然不考虑这些更改。因此,如果实体未刷新,实体方法似乎不考虑对数据库的刷新更改。可能是基本的东西,但我不知道。我希望这会为某人省去很多麻烦。

最新更新