2017-09-16 63 views
0

我有一個多對多關係的擁有方列表。如何使用Grails GORM在一個查詢中查詢所有擁有的對象?在SQL中,我將使用連接表和擁有的表以及具有in子句的擁有表的id。如何在一個查詢MTM中查詢所有擁有的對象?

實例域類:

class Book { 
    static belongsTo = Author 
    static hasMany = [authors:Author] 
    String title 
} 

class Author { 
    static hasMany = [books:Book] 
    String name 
} 

所以我有作者的列表或集,我想找到他們的所有圖書在一個查詢。

select b.* 
    from book b 
    join author_book ab on b.id = ab.book_id 
where ab.author_id in (1, 2, 3); 

在Grails中,我嘗試了以下,但它失敗了。

def books = Book.withCriteria { 
    inList('authors', authors) 
} 
+0

的可能的複製[節點的Postgres:如何執行 「WHERE山坳IN(<動態值列表>)」 查詢?](HTTPS: //sackoverflow.com/questions/10720420/node-postgres-how-to-execute-where-col-in-dynamic-value-list-query) – lad2025

+0

這是相當複製的:[grails grom創建標準與許多-many映射](https://stackoverflow.com/questions/43959938/grails-grom-create-criteria-with-many-to-many-mapping) – gregorr

回答

0

您需要先加入作者:

def books = Book.withCriteria { 
    authors { 
     inList('id', authors*.id) 
    } 
} 
0

這是你在找什麼?

Book.findAllByAuthorInList(authors) 
相關問題