简体   繁体   English

如何在Grails条件查询中引用“ this”对象

[英]How can I refer to the “this” object in a Grails criteria query

I have a set of domain objects that are related like this: 我有一组与此相关的域对象:

class Book {
    static belongsTo = [author: Author]
}

class Contract {
    static belongsTo = [author: Author]
    Book book
}

class Author {
     static hasMany = [books: Book, contracts: Contract]
}

I'd like to create a query that joins against all a book's author's contracts where the contract book is "this" book. 我想创建一个查询,该查询将所有书的作者的合同合并为合同书,即合同书为“本”书。 The question I want to answer is "what are all books under contract?" 我要回答的问题是“所有书籍都在合同中?” Here what I have for the criteria, but I don't know how to refer to the "this" object: 这是我要满足的条件,但是我不知道如何引用“ this”对象:

Book.createCriteria().list() {
    author {
        contracts {
            eqProperty('book', '??') // what here??
        }
    }
}

Can I refer to the "this" object or somehow create an alias for it? 我可以引用“此”对象还是以某种方式为其创建别名?

did not write up a unit test, but I think you can do this.. 没有写单元测试,但是我认为你可以做到。

GORM Documentation Scroll down to eager fetching example to see example GORM文档向下滚动以获取示例以查看示例

Book.createCriteria().list() {
    author {
        contracts {
            eqProperty('book.id', book.id) // what here??
        }
    }
}

Instead of using the Criteria builder, is straight HQL an option? 除了使用“条件”构建器之外,是否可以选择直接HQL? I'm not the most fluent in HQL, but perhaps could you do something like: 我不是HQL上最流利的人,但也许您可以执行以下操作:

// should return a collection of Books
Contract.executeQuery('select distinct c.book from Contract c')

If you need it to be for a specific Author, you can add a where clause accordingly ( docs ). 如果需要用于特定的Author,则可以相应地添加where子句( docs )。

Without having a version of grails running on this machine I was unable to test this for syntax. 如果没有在此计算机上运行grails版本,则无法测试其语法。

You may be able to do something like this: add "import org.hibernate.FetchMode as FM" to your Controller or Service 您可能可以执行以下操作:将“ import org.hibernate.FetchMode as FM”添加到Controller或Service

Contract.withCriteria{
    createAlias('book','b')
    fetchMode('book',FM.EAGER)
}.book.unique()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM