2016-04-12 45 views
0

如何爲Grails數據庫遷移插件編寫changelog.groovy插件,該插件將行插入表中,如果某行尚不存在一定範圍的ID?例如。grails數據庫遷移插件 - 如何有條件地插入行

cool_stuff table has id | some_other_id |

cool_stuff表中填充了數據。給定一個範圍cool_stuff的ID,1 - 2000年,我想:

  1. 遍歷相應的ID,查詢cool_stuff表,看是否cool_stuff ID和組合some_other_id = 2存在
  2. 如果它不「噸存在,插入一行與cool_stuff ID和some_other_id = 2
+0

這可以在changelog.xml而不是changelog.groovy中完成嗎? – ddelponte

回答

0
  1. Threre上 「cool_stuff」 表已經recoreds。
  2. 你需要記錄的conbination說: 「cool_stuff.id」 和 「some_other_id == 2」

所以,你要像下面?

table of "cool_stuff" 

FROM: 
id | some_other_id 
----|--------------- 
1 | 2 
2 | 1 
3 | 2 
4 | 1 

TO: 
id | some_other_id 
----|--------------- 
1 | 2 
2 | 1 
3 | 2 
4 | 1 
2 | 2 
4 | 2 

這是對嗎?
如果我這樣做,我想要做的如下。

databaseChangeLog = { 
    changeSet(author: "koji", id: "123456789") { 
     grailsChange { 
      change { 
       CoolStuff.list().findAll { 
        it.someOtherId != 2 
       }.each{ 
        // save new instance 
        new CoolStuf(id: it.id, someOtherId:2).save(flush:true) 
       } 
      } 
     } 
    } 
}