简体   繁体   中英

how to make a field auto increment in a table in grails? and when deleted it adjust the other records

I have a Table called Trip where the users can create trips, and on the edit screen I have a button that the users can click on it and create Legs for that selected trip. my question is how do I make a field in the TripLegs domain auto increment? so lets say the user creates four trip legs, so the stop number field "the one I wanted to auto populate" would be 1 2 3 4 if the user goes back and delete Trip leg 2 so how do I change the stop number in the rest three legs to 1 2 3 instead of 1 3 4 在此处输入图片说明

I have to agree with Vahid's comment on the original question. My preferred approach would be to dynamically set that value as a transient value on the domain after I sorted the collection by some criteria.

If you wanted to maintain the same sort order every time based on which Leg was created sequentially, you could add a 'Created_Date' column to your table and sort based on that value when you get the list.

Alternatively, if you would really like to store the stop_number value (which there are plenty of reasons why you might want to) you might want to consider the following approach:

Override the default Delete action for TripLegs:

class TripLegController {
  def delete = {
    def tripLegId = params.tripLegId as Long
    def tripLeg = TripLeg.get(tripLegId)
    def otherLegs = TripLeg.FindAllByTripAndIdNotEqual(tripLeg.trip, tripLegId, [sort: 'stopNumber', order: 'asc'])
    tripLeg.delete(failOnError: true)
    def stopNum = 1
    otherLegs.each{leg -> 
      leg.stopNumber = stopNum
      leg.save()
      stopNum++
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM