【问题标题】:Grails GORM Query with Multiple Objects?带有多个对象的 Grails GORM 查询?
【发布时间】:2013-03-02 15:01:11
【问题描述】:

我正在尝试在 Grails 中编写查询以从域类返回一组结果,但在这些结果中返回具有主类的 parentId 的单独类的相关结果。

    def query = Cars.where {
        (colour == 'red') 
    }

然后在每个列表项中包含与该 CAR ID 相关的一组部分(作为我想要实现的示例,我知道代码不正确......

    query.each{ 
          this car. add(Parts.whereCarID{it.id})
     }

【问题讨论】:

    标签: grails grails-orm


    【解决方案1】:

    如果你正确地定义了你的领域模型,你应该在不涉及标准的情况下得到它。 据我了解,您需要在 Cars 域类中添加 static hasMany = [parts: Parts],在 Parts 类中添加 static belongsTo = [car:Cars]

    举个例子,它的外观如下:

    class Cars {
        string colour
        static hasMany = [parts:Parts]
        // ... rest of your properties 
    }
    
    class Parts {
        static belongsTo = [car:Cars]
        // ... rest of your properties 
    }
    

    要得到你的结果,只需这样做:

    def cars = Cars.findAllByColour('red')
    

    那么你可以这样做:

    cars.each { car->
        println car.parts // <-- all the parts for each car is here
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-23
      • 1970-01-01
      • 2014-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多