2013-10-10 81 views
0

在下面的代碼如何刪除與作者assoicated所有的舊商店記錄,並插入一個新的Grails的Groovy中刪除舊記錄

域類

class Store { 
Date dateCreated 
Date lastUpdated 

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

域控制器

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 
    } 
} 
+2

你可以添加'Author'類的源代碼嗎?沒有它就無法給予解決方案。 – rxn1d

回答

0

我假設你已經檢索到你想修改的Author實例。在這種情況下,您只需遍歷與作者相關的商店並逐個刪除它們即可。無論你想在每次刪除後刷新還是等到全部刪除都由你決定。

假設你有一個Author類,看起來是這樣的:

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

那麼你可以添加方法來你的控制器:

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

另一種方法是在域類添加這些方法,這可能是更可取的,特別是如果你的應用程序需要它們多於一個的話。