在列表中找到所有具有值的对象 [英] Find all objects with value in list

查看:83
本文介绍了在列表中找到所有具有值的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在向Grails环境介绍自己(这是真棒)。我一直在收获动态生成方法的好处,如 findAllBy * 范围。但是,我遇到了一个问题,我不确定如何继续。在Google上花费的一小时对我来说并没有那么多。

问题


$ b $我有一个类如下:

  class Runner {

static hasMany = [Owner:Owner]
}

在我的Owner控制器中,我希望找到所有 Runner 包含给定所有者的对象。实际上,我试图从多个一个



示例

如果我有一个所有者看起来像

 所有者[name =Dave] 

我有一个 Runner 类似于:

 Runner [拥有者[Owner [name =Dave],Owner [name =James]]] 

我的查询应该返回这个 Runner 对象,但它不应该返回

  Runner [拥有者[Owner [name =Bill],Owner [name =James]]] 

我的尝试



我试图使用 inList 扩展,但经过一些进一步的研究后,我意识到这是为其他方式设计的。我的代码目前如下:

  def runners(){
log.info(Runners)
List< Runner>亚军;
业主;

if(params.id){
log.info(Id =+ params.id);
owner = Owner.get(params.id);
log.info(owner =+ owner.name);
//在列表中抓住跑步者。
log.info(Number of results =+ runners.size());
}


[results:results,jockeyInstance:jockey]
}

$经过对 HQL 的一些研究,我发现了一个更优雅的解决方案,它并不需要我完全可以改变 Domain 类。我使用的查询如下所示:

  runners = Runner.executeQuery(FROM Runner as r WHERE:owner in elements(r .owners),[owner:ownerInstance]); 

其中 ownerInstance 所有者用于映射到 Runner 的对象。


I'm introducing myself to the Grails environment (It's awesome). I've been reaping the benefits of dynamically generated methods like the findAllBy* range. However, I've come to a problem and I'm unsure about how to proceed. An hour spent on Google didn't yield all that much for me either.

Problem

I have a class like the following:

class Runner {

    static hasMany = [owners: Owner]
}

And in my Owner controller, I wish to find all Runner objects, that contain a given Owner. Effectively, I'm trying to go from the many to the one.

Example

If I have an Owner object, that looks something like

Owner[name="Dave"]

And I have a Runner with something like:

Runner[owners[Owner[name="Dave"], Owner[name="James"]]]

My query should return this Runner object, but it should not return

Runner[owners[Owner[name="Bill"], Owner[name="James"]]]

My attempts

I've attempted to use the inList extension, but after some further research I realised that was designed for the other way around. My code at the moment is as follows:

def runners() {
    log.info("Runners")
    List<Runner> runners;
    Owner owner;

    if (params.id) {
        log.info("Id = " + params.id);
        owner = Owner.get(params.id);
        log.info("owner = " + owner.name);
        // Grab runners in list thing.
        log.info("Number of results = " + runners.size());
    }


    [results: results, jockeyInstance: jockey]
}

解决方案

After some research into HQL, I found a more elegant solution that didn't require me to change the Domain classes at all. The query I used was as follows:

runners = Runner.executeQuery("FROM Runner as r WHERE :owner in elements(r.owners)", [owner : ownerInstance]);

Where ownerInstance is the Owner object being used to map to the Runner.

这篇关于在列表中找到所有具有值的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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