我有一个简单的数组,其中包含一些需要插入数据库的值。在所有值中,实际上仅插入了最后一个。
当我将flush();
放入循环中时,确实插入了记录。
当我在刷新(在foreach之外)之前转储实体管理器时,确实看到了对所有值(实体)的引用。
尽管,仅插入最后一条记录。它确实获得了ID#3,因此似乎其他人在某个地方迷路了。
$values = [
"val1", "val2", "val3"
];
foreach ($values as $value) {
$i = new MyEntityClass();
$i->setVerified(false);
$i->setName($value);
$this->em->persist($i);
}
$this->em->flush();
更新:我挂接了一个事件监听器以在刷新前和刷新后使用。
public function preFlush(PreFlushEventArgs $args) {
$em = $args->getEntityManager();
foreach ($em->getUnitOfWork()->getScheduledEntityInsertions() as $entity) {
dump($entity->getName());
}
}
public function postFlush(PostFlushEventArgs $args) {
dd($args->getEntityManager()->getUnitOfWork()->getScheduledEntityInsertions());
}
在preFlush中,所有值均清晰打印,并且postFlush转储为空。
更新2:我正在使用如下的uuid_binary_ordered_time
/**
* @ORM\Id
* @ORM\Column(type="uuid_binary_ordered_time", unique=true)
* @GeneratedValue(strategy="CUSTOM")
* @CustomIdGenerator(class="Ramsey\Uuid\Doctrine\UuidOrderedTimeGenerator")
* @Groups({"uuid"})
*/
protected $id;
使用10.4.8-MariaDB
和php v7.3.10
为什么您在这样的持久化之后不立即使用冲洗:
$values = [
"val1", "val2", "val3"
];
foreach ($values as $value) {
$i = new MyEntityClass();
$i->setVerified(false);
$i->setName($value);
$this->em->persist($i);
$this->em->flush();
}
或更好:
public function save(MyEntityClass $myEntityClass): void
{
$this->em->persist($myEntityClass);
$this->em->flush();
}
在实体的存储库中,并在您要单独保存相关实体时使用它
编辑-另一种尝试的方法
$values = [
"val1", "val2", "val3"
];
$this->em->getConnection()->beginTransaction();
foreach ($values as $value) {
$i = new MyEntityClass();
$i->setVerified(false);
$i->setName($value);
$this->em->persist($i);
}
try {
$this->em->flush();
$this->em->getConnection()->commit();
} catch (Exception $e) {
$this->em->getConnection()->rollback();
$this->em->close();
throw $e;
}
还要在$ id的定义中添加行:
/**
* @var \Ramsey\Uuid\UuidInterface
*
* @ORM\Id
* @ORM\Column(type="uuid_binary_ordered_time", unique=true)
* @GeneratedValue(strategy="CUSTOM")
* @CustomIdGenerator(class="Ramsey\Uuid\Doctrine\UuidOrderedTimeGenerator")
* @Groups({"uuid"})
*/
protected $id;
编辑-使用type =“ uuid”
更新$ id的声明
/**
* Entity constructor.
*
* @param UuidInterface|null $uuid
*
* @throws \Exception
*/
public function __construct(UuidInterface $uuid = null)
{
if (null === $uuid) {
$uuid = Uuid::uuid4();
}
$this->id = $uuid;
[Other fields ...]
}
/**
* @var \Ramsey\Uuid\UuidInterface
*
* @ORM\Id
* @ORM\Column(type="uuid")
*/
protected $id;
/**
* @return UuidInterface|null
*/
public function getId(): ?UuidInterface
{
return $this->id;
}
这样做,您应该排除与Doctrine纠缠是$ id ...,我们可以在其他地方进行调查