[英]Doctrine 2 creating multiple records
我試圖通過Doctrine創建多個記錄,但遇到一個奇怪的問題,它將成功創建第一個記錄,但沒有其他記錄。 說我有以下內容,其中Record是一個Doctrine實體,而record_id是主鍵:
$entityManager->getConnection()->beginTransaction();
foreach($recordsToCreate as $data)
{
$record = new Record();
$record->field1 = $data['field1'];
$record->field2 = $data['field2'];
$entityManager->persist($record);
$entityManager->flush();
}
$entityManager->getConnection()->commit();
如果我有三個記錄,則第一個記錄將正確創建,而其他兩個記錄則不能正確創建。 沒有引發錯誤或異常,但是沒有在數據庫中創建記錄。 如果在刷新后輸出每條記錄,則所有字段均已正確設置,但第一條記錄后主鍵為null。 我以為這是一個錯誤准則,但我想確定在提交錯誤報告之前。
謝謝。
弄清楚了-答案不是如上所述將flush()放在循環之外。 解決方案是在提交事務后使用detach()。 所以:
foreach($recordsToCreate as $data)
{
$entityManager->getConnection()->beginTransaction();
$record = new Record();
$record->field1 = $data['field1'];
$record->field2 = $data['field2'];
$entityManager->persist($record);
$entityManager->flush();
$entityManager->getConnection()->commit();
$entityManager->detach($record);
}
現在對我有用。 問題在於(我認為)實體管理器無法區分第一條記錄和其余記錄之間的區別,因此分離確保了在進行創建時總是有一條新記錄。 另外,由於我實際上是在實際代碼中使用該記錄創建/修改其他記錄,因此事務現在處於循環中,因此將其放入循環中對我的設置更為准確。
簡而言之,在提交后在新記錄上調用detach,這對我來說都是有好處的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.