【问题标题】:GORM query criteria for nested hasOne entity嵌套 hasOne 实体的 GORM 查询条件
【发布时间】:2016-07-13 12:22:15
【问题描述】:

我正在尝试通过子实体的属性创建 GORM 条件查询过滤。所以有这样的实体:

class PaymentEntry {

  static hasOne = [category: PaymentCategory]

  static constraints = {
    category(nullable: true)
  }

  // other stuff
}

class PaymentCategory {

  static hasMany = [payments: PaymentEntry]

  // other stuff  
}

现在我正在尝试选择具有特定类别的 PaymentEntries。我正在尝试这样的事情:

def c = PaymentEntry.createCriteria()

def res = c {
  'in'("category", categories)
}

categories 这里是PaymentCategory 实体的列表,之前已选择。

不幸的是,这失败了。 Grails 抛出 NoSuchMethodException。

【问题讨论】:

  • 哪个 Grails 版本?

标签: grails grails-orm


【解决方案1】:

你应该有 inList。 试试这个:

def res = c {
  inList("category", categories)
}

【讨论】:

    【解决方案2】:

    有很多问题。 hasOne 是一对一的associations,但实际上你是一对多的。所以第一步是修复关联,可能是这样的:

    class PaymentEntry {
    
      static belongsTo = [category: PaymentCategory]
    
      static constraints = {
        category(nullable: true)
      }
    
      // other stuff
    }
    
    class PaymentCategory {
    
      static hasMany = [payments: PaymentEntry]
    
      // other stuff  
    }
    

    接下来,一旦您有了条件实例,您需要调用其方法之一,例如list(),来构建和执行您的查询。

    def c = PaymentEntry.createCriteria()
    
    def res = c.list {
      'in'("category", categories)
    }  
    

    同一事物的较短版本是...

    def res = PaymentEntry.withCriteria {
      'in'("category", categories)
    }  
    

    in()inList() 都可供您使用,只要您像以前那样引用 in,因为它是一个 Groovy 关键字。你可以阅读更多关于条件查询here

    【讨论】:

    • 但我不想在 PaymentCategory 中有 payments 字段。我真的需要它吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-24
    • 1970-01-01
    相关资源
    最近更新 更多