开发者

How can I refer to the "this" object in a Grails criteria query

开发者 https://www.devze.com 2023-01-23 00:04 出处:网络
I have a set of domain objects that are related like this: class Book { static belongsTo = [author: Author]

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开发者_Go百科 have for the criteria, but I don't know how to refer to the "this" object:

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

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


Instead of using the Criteria builder, is straight HQL an option? I'm not the most fluent in HQL, but perhaps could you do something like:

// 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).


Without having a version of grails running on this machine I was unable to test this for syntax.

You may be able to do something like this: add "import org.hibernate.FetchMode as FM" to your Controller or Service

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号