简体   繁体   English

Grails命名查询-通过关联查找

[英]Grails named query - find by association

I want to create a named query that will find all objects of one class, based on a property (or properties) of child class properties. 我想创建一个命名查询,该查询将基于子类属性的一个或多个属性找到一个类的所有对象。

I want to be able to find all Bars where Foo.me == "some string" 我希望能够找到所有Foo.me ==“ some string”的酒吧

So, I have this, and it doesn't work: 所以,我有这个,它不起作用:

class Foo {
    String me
}

class Bar {
    Foo foo

    static namedQueries = {
        findByFooMe { meStr ->
            eq(foo.me, meStr)
        }
    }
}

What does the correct syntax look like please? 正确的语法是什么样的? Also, how does it change if Bar hasMany Foos, and I want to find all Bars where one of its Foo,me properties is "search string"? 另外,如果Bar具有很多Foos,并且我想查找其Foo,me属性之一是“搜索字符串”的所有Bar,它将如何改变?

ie

class Bar {
    static hasMany [foos: Foo]
} 

While I wouldn't recommend using findBy as the prefix to a named query, you are close to having the right implementation. 虽然我不建议将findBy用作命名查询的前缀,但是您接近正确的实现。 Here is an updated version with a new name for the query too. 这也是该查询的更新版本,也带有新名称。

static namedQueries = {
    locateByFooMe { meStr ->
        foo {
          eq('me', meStr)
        }
    }
}

If you change your relationship to a collection (One to Many) just make sure the property name foo (in this case) changes to whatever you change it to ( foos in your question) and the above query will still continue to work. 如果您更改与集合的关系(一对多),只需确保将属性名称foo (在这种情况下)更改为您将其更改为的任何名称(问题中的foos ),以上查询仍将继续起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM