grails - 保存新记录时动态发现关系的更好方法? (对方失败)

标签 grails dynamic grails-orm one-to-many

鉴于这种关系:

class A {
    String name
    static hasMany = [b:B]
}
class B {
    String name
    static belongsTo = [a:A]
}

我有一条要保存的记录 b。我已经通过工作 Grails 反射(在下面的代码示例中省略)发现它需要是 B 类的一个实例。除此之外,记录b只知道:
  • 它有一个关系“a”
  • 关系“a”的键

  • 由于是动态案例,我们不知道但必须发现:
  • 关系“a”是 的一个实例A类 (所以我们可以调用 A .find(a's key))
  • 关系的“另一面”——A 类的观点——是关系“ b ”(所以我们可以调用 .addToB (b))

  • 那么如何将 b 保存到数据库中呢?这是我的做法:
    class AssocTests extends GrailsUnitTestCase {
        protected void setUp() {
            super.setUp()
            // I don't know this part, but it's in the DB
            def a = new A(name:"al")
            a.save()
        }
    
        void testAssociation() {
            // I want to create a new B such that name="bob"
            // I also had to discover "class B" using (working) Grails reflection
            // but omitted it for this example.
            def b = new B(name:"bob")
            // ... and the relation is as "given" below
            def given = [a:[name:"al"]]
            // So I need to call A.find([name:"al"]).addToB(b).  But "A" and
            // "addToB" are unknown so need to be found via reflection
            def gdc = new DefaultGrailsDomainClass(B)
            given.each { give ->
                def prop = gdc.getPropertyByName(give.key)
                if (prop.isAssociation() && !prop.isOwningSide()) {
                    println "I want to use otherSide, but it's ${prop.otherSide}"
                    def os = reallyGetOtherSide(B, give)
                    def object = os.parent.find(
                            os.parent.newInstance(give.value))
                    object."${os.method}"(b)
                }       
            }       
            def bFound = B.findByName("bob")
            assertEquals "al", bFound.a.name
        }
    
        def reallyGetOtherSide(clazz, relation) {
            def parent=clazz.belongsTo[relation.key] 
            def addTo=parent.hasMany.find { (clazz == it.value) }.key
            [parent:parent, method:"addTo${addTo.capitalize()}"]
        }
    }
    

    ...不幸的是, otherSide 返回 null。这不可能是最好的方法,不是吗?

    最佳答案

    如果我理解正确,您可以引用这些文档 here .您可以尝试以下方法:

      `new A(name:"Gatwick")
             .addToB(new B(name:"BA3430"))
             .addToB(new B(name:"EZ0938"))
             .save()`
    

    关于grails - 保存新记录时动态发现关系的更好方法? (对方失败),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5827779/

    相关文章:

    mysql - 如何从csv文件中获取数据并用mysql保存到grails中?

    swift - HTTP 请求 PUT 文件(图像)到 Swift RESTful API (Grails)

    android - 多个RadioButton可以在一个RadioGroup android中被选中

    grails - 在Grails中的投影

    grails - 如何在特定数据源上调用 Grails namedQuery?

    grails - GORM 使用外键而不是域对象

    html - Grails中的数据列表

    grails - 更新不获取 “updated”数据

    在没有 C 库的情况下创建和调整动态数组?

    hibernate - GORM - 在 Grails 中查询一对多关联