【问题标题】:How to query all the owned objects in one query MTM?如何在一个查询 MTM 中查询所有拥有的对象?
【发布时间】:2017-09-16 06:13:56
【问题描述】:

我有一个多对多关系拥有方的列表。如何使用 Grails GORM 在一次查询中查询所有拥有的对象?在 SQL 中,我将使用连接表和拥有的表以及拥有表的 id 和 in 子句。

域类示例:

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)
}

【问题讨论】:

标签: postgresql grails grails-orm


【解决方案1】:

你需要先加入作者:

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

【讨论】:

    【解决方案2】:

    这就是你要找的吗?

    Book.findAllByAuthorInList(authors)
    

    【讨论】:

      猜你喜欢
      • 2021-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多