سؤال

In the following code how can i delete all the old stores record assoicated with an author and insert a new one

Domain class

 class Store {
Date dateCreated
Date lastUpdated

static belongsTo = [author: Author]
    static constraints = {
     }
  }

domain controller

 def update() {
    if (!requestIsJson()) {
        respondNotAcceptable()
        return
    }

    def bookInstance = book.get(params.id)
    if (!bookInstance) {
        respondNotFound params.id
        return
    }

    if (params.version != null) {
        if (bookInstance.version > params.long('version')) {
            respondConflict(bookInstance)
            return
        }
    }

    def stores = bookInstance.stores

    //bookInstance.delete(flush:true);
    //stores.delete(flush:true);



    bookInstance.properties = request.GSON

    if (bookInstance.save(flush: true)) {
        respondUpdated bookInstance

    } else {
        respondUnprocessableEntity bookInstance
    }
}
هل كانت مفيدة؟

المحلول

I'm assuming you have retrieved the Author instance that you want to modify. In that case, you can simply iterate over the stores associated with the author and delete them one by one. Whether you want to flush after each delete or wait until all are deleted is up to you.

Assuming you have an Author class that looks something like this:

class Author {
    static hasMany = [stores: Store]
}

Then you can add methods to your controller:

class MyController {
    SessionFactory sessionFactory

    def deleteStoresFromAuthor(Author author) {
        author.stores.each { it.delete(flush: true) }
    }

    def deleteStoresFromAuthorWithDelayedFlush(Author author) {
        author.stores.each { it.delete() }
        sessionFactory.currentSession.flush()
    }

    def createStoreForAuthor(Author author) {
        new Store(author: author, dateCreated: new Date(), lastUpdated: new Date()).
                save(flush: true)
    }
}

Another alternative is to add these methods in the domain classes, which might be preferable, especially if you need them more than one place in your application.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top