问题
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:
- Dump the pertinent records in order into a new table,
- Add a field called
new_orderthat is an autonumber field, - Join the tables on the
idfield and updatecurrent_table.order = new_table.new_order, - 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:
- 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)
- Order the rows (this could also have been done previously within the SQL query)
- Update the rows using a counter, exactly like you have proposed
来源:https://stackoverflow.com/questions/29355394/how-to-renumber-a-column-in-doctrine