【问题标题】:grails database migration plugin - how to conditionally insert rowsgrails 数据库迁移插件 - 如何有条件地插入行
【发布时间】:2016-08-03 06:13:48
【问题描述】:

我如何为 grails 数据库迁移插件编写一个 changelog.groovy,如果某个 id 范围内的行不存在,它将向表中插入行?例如。

cool_stuff 表有 编号 | 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 的行

【问题讨论】:

  • 这可以在 changelog.xml 而不是 changelog.groovy 中完成吗?

标签: grails database-migration liquibase


【解决方案1】:
  1. “cool_stuff”表中已有 3 个记录。
  2. 您需要组合“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)
                }
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-07
    • 2012-05-20
    • 2019-08-31
    • 2013-09-02
    • 1970-01-01
    • 2014-05-19
    • 2012-05-28
    相关资源
    最近更新 更多