How to renumber a column in doctrine

社会主义新天地 提交于 2020-02-07 03:41:09

问题


I am developing a project in zf2 using doctrine and I need to create a method to renumber the order field so that the values are sequential. Before:

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

After:

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

The order sequences are by collection, but I don’t need the method to renumber the entire dataset; just the records in a particular collection.

Some of the solutions I am considering include:

Temporary Table:

  1. Dump the pertinent records in order into a new table,
  2. Add a field called new_order that is an autonumber field,
  3. Join the tables on the id field and update current_table.order = new_table.new_order,
  4. Delete the temporary table.

Cycle Through the Records and Update one at a Time:

$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
}

Any other thoughts?


回答1:


Very much, definitely, please, use the 2nd method... I.E. cycle through records and update.

Quick reason for not using temp tables:

  • If you're using a MySQL temporary table, it is visible to the current session; which could actually be shared by multiple sessions if you are using persistent connections. If you run the script twice at the same time, it could cause some data corruption. The same thing applies to creating real tables.

What you should do is:

  1. Retrieve all your data, or at least retrieve them in logical batches (in this case, it could be done by retrieving only rows of a particular "collection", e.g. fruits)
  2. Order the rows (this could also have been done previously within the SQL query)
  3. Update the rows using a counter, exactly like you have proposed


来源:https://stackoverflow.com/questions/29355394/how-to-renumber-a-column-in-doctrine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!