gpt4 book ai didi

php - Make Doctrine 以原始顺序添加实体

转载 作者:行者123 更新时间:2023-12-02 17:31:23 27 4
gpt4 key购买 nike

我有以下代码:

$em = $this->getDoctrine()->getManager();

$evaluation->getQuestions()->clear();

foreach ($questions_data as $data) {
$id = (int) $data['id'];

if ($id > 0) {
$question = $em->getRepository('MyBundle:Question')->find($id);

if ($question)
$evaluation->getQuestions()->add($question);
}
}

$em->persist($evaluation);
$em->flush();

这里是 $questions_dataarray(['id' => 2], ['id' => 1], ['id' => 3]).
以下是学说如何将问题存入数据库:
enter image description here

那么,如何让学说不对问题进行排序呢?
Evaluation 实体与 Question 实体具有 ManyToMany 关系,因此 ORDER BY 无济于事,因为表 evaluations_questionsDoctrine 自动创建,没有字段 id

最佳答案

当你刷新 Doctrine 中新的持久化项时,Doctrine 必须使用内部函数 getCommitOrder 来确定将它们提交到数据库的顺序。 .该函数的目的是确保在提交对象本身之前提交对象的依赖项。这样做是为了遵守可能设置的任何外键约束。正如您所观察到的,按这样的顺序提交数据的结果是您无法微调项目的提交顺序 - 这不一定是坏事

在 SQL 中,您可以对结果进行排序的唯一方法是使用 ORDER BY 发出查询。如果您选择不指定排序方法,则不能期望结果以任何特定顺序返回。 PostgreSQL docs解释一下:

If sorting is not chosen, the rows will be returned in an unspecified order. The actual order in that case will depend on the scan and join plan types and the order on disk, but it must not be relied on.

换句话说,内容存储在数据库中的顺序无关紧要。

在您的问题中,向用户显示问题的顺序是一个问题。您不能让问题在评估中随机出现 - 它们必须遵循预设顺序。 Frankbeen 在评论中提到了这一点,但最好的解决方案是在 Evaluation 上添加一个新字段来存储 array 问题的正确顺序。当您向用户展示评估时,可以读取订单。


如果您绝对必须在数据库中以特定顺序对它们进行排序,您应该能够在新对象持久化时单独刷新它们,而不是安排它们一起刷新。 p>

$em = $this->getDoctrine()->getManager();

$evaluation->getQuestions()->clear();

foreach ($questions_data as $data) {
$id = (int) $data['id'];

if ($id > 0) {
$question = $em->getRepository('MyBundle:Question')->find($id);

if ($question) {
$evaluation->getQuestions()->add($question);
$em->persist($evaluation);
$em->flush();
}
}
}

请注意,这将需要更多时间才能完成,并且对于您的问题而言,这是一个非常糟糕的解决方案。

关于php - Make Doctrine 以原始顺序添加实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32766709/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com