如何在学说中重新编号一列


How to renumber a column in doctrine

我正在zf2中使用条令开发一个项目,我需要创建一种方法来重新编号order字段,以便值是连续的。之前:

+-----+-------+--------+------------+
|  id | order | item   | collection |
+-----+-------+--------+------------+
| 987 |     1 | apple  | fruits     |
|  46 |     2 | banana | fruits     |
| 394 |     7 | grape  | fruits     |
| 265 |    30 | pear   | fruits     |
|  89 |     1 | squash | vegetables |
+-----+-------+--------+------------+

之后:

+-----+-------+--------+------------+
|  id | order | item   | collection |
+-----+-------+--------+------------+
| 987 |     1 | apple  | fruits     |
|  46 |     2 | banana | fruits     |
| 394 |     3 | grape  | fruits     |
| 265 |     4 | pear   | fruits     |
|  89 |     1 | squash | vegetables |
+-----+-------+--------+------------+

顺序序列是通过collection,但我不需要对整个数据集重新编号的方法;只是某个特定集合中的记录。

我正在考虑的一些解决方案包括:

临时表格:

  1. 将相关记录按顺序转储到新表中
  2. 添加一个称为CCD_ 3的字段,该字段是一个自动编号字段
  3. 加入CCD_ 4字段上的表并更新CCD_
  4. 删除临时表

循环浏览记录并一次更新一个:

$collection = … // results from select query where collection=fruits
n  = 1;
For each ($collection as $item) {
// update query to set order=n where id=$item[id]
n += 1
}

还有其他想法吗?

非常,当然,请使用第二种方法。。。即循环浏览记录和更新。

不使用临时表的快速原因:

  • 如果您使用的是MySQL临时表,那么它对当前会话是可见的;如果您使用持久连接,它实际上可以由多个会话共享。如果同时运行两次脚本,可能会导致一些数据损坏。同样的事情也适用于创建真实的表

你应该做的是:

  1. 检索所有数据,或者至少按逻辑批次检索数据(在这种情况下,可以只检索特定"集合"的行,例如水果)
  2. 对行进行排序(以前也可以在SQL查询中执行此操作)
  3. 使用计数器更新行,与您建议的完全一样