Grails:我如何通过hasMany关系搜索孩子? [英] Grails: How can I search through children in a hasMany relationship?

查看:101
本文介绍了Grails:我如何通过hasMany关系搜索孩子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个客户端域类,并且该客户端有许多课程。我如何找到我要找的课程?例如:

  class客户端{
字符串名称
static hasMany = [courses:Course]

$ b $课程{
字符串名称
static belongsTo = [客户端:客户端]
}

def client = Client。 get(1)

我想在该课程关系中查找或搜索。可能是这样的:

  client.courses.find(name:'Whatever')

有什么办法可以用Grails做到这一点吗?

解决方案

如果您正在使用二级缓存并为此关联进行了配置,则可能需要遍历集合(如果关联位于缓存中,这将为您节省数据库查询)。

b
$ b

下面是一个巧妙的例子: Groovy Collection API

  def course = client.courses.find {it.name ==whatever } 

重要提示:如果您决定采取这种方法,请确保配置提前/批量提取 课程,所以你不会碰到 n + 1问题

If I have a Client domain class, and that Client hasMany Courses. How do I find the course I'm looking for? For instance:

class Client {
    String name
    static hasMany = [courses:Course]
}

class Course {
    String name
    static belongsTo = [client:Client]
}

def client = Client.get(1)

I want to "find" or "search" within that courses relationship. Maybe something like:

client.courses.find(name:'Whatever')

Is there any way to do this with Grails?

解决方案

If you're using a second level cache and have configured it for this association, you might want to iterate over the collection (this will save you a database query if the association is in cache).

Here is an example using the clever Groovy Collection API:

def course = client.courses.find { it.name == "whatever" }

Important: If you decide to take this approach make sure to configure eager / batch fetching of courses so you don't run into the n+1 problem.

这篇关于Grails:我如何通过hasMany关系搜索孩子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆