2017-09-16 75 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) 
相关问题