[英]How to query on a many to many relationship in Grails?
I have the following Domain Classes: 我有以下域类:
class PreparedToWork {
String location
static hasMany = [assessors: Assessor]
}
class Assessor {
//Some Properties
static belongsTo = [PreparedToWork]
static hasMany = [preparedToWork: PreparedToWork]
}
I would like to retrieve all of the Assessors which are prepared to work in a certain location with only the prepared to work ID. 我想使用仅准备工作ID来检索准备在某个位置工作的所有评估员。 I have my join table in the actual database so I'm certain the relationship is fine however have tried various querying options and have failed miserably.
我在实际数据库中有我的联接表,所以我确定这种关系很好,但是尝试了各种查询选项,但失败了。
App info: 应用信息:
I think the following is a much more natural way to describe your domain 我认为以下是描述您的域的更自然的方法
class Location {
String name
static hasMany = [preparedToWork: Assessor]
}
class Assessor {
//Some Properties
static belongsTo = [Location]
static hasMany = [preparedToWork: Location]
}
Then you can retrieve all of the assessors who are prepared to work in a certain location with 然后,您可以检索准备在某个位置工作的所有评估员,
Assessor.executeQuery(
"from Assessor a join a.preparedToWork l where l.id = ?", [locationId])
I would setup my domains a little different than what you have. 我将设置的域与您的域有所不同。 Here is an example.
这是一个例子。
class Location{
String name
static hasMany = [assessors: Assessor]
static mapping = {
assessors joinTable: [name: 'preparedToWork', key:'location_id']
}
}
class Assessor {
static belongsTo = [Location]
static hasMany = [locations: Location]
static mapping = {
assessors joinTable: [name: 'preparedToWork', key:'assessor_id']
}
}
Once the domains are setup like this, I expect to see 3 tables location assessor preparedToWork : composite key of location_id and assessor_id 像这样设置域后,我希望看到3个表位置评估器prepareToWork:location_id和评估者ID的复合键
If I need to find all the assessors for a specific location, I can use following statements. 如果需要查找特定位置的所有评估者,则可以使用以下语句。
def location = Location.where{ name == "some-location" }
def assessors = location.assessors //
Hope this helps. 希望这可以帮助。
After trying many different types of queries I used a detached query. 在尝试了许多不同类型的查询之后,我使用了分离查询。 I did try solution 1 however I was also querying on many other properties and the query below allowed me to do that.
我确实尝试了解决方案1,但是我也在查询许多其他属性,下面的查询允许我这样做。
def criteria = new DetachedCriteria(Assessor)
if (preparedToWork) {
criteria = criteria.build {
createAlias("preparedToWork", "p")
eq("p.id", preparedToWork)
}
}
criteria.list()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.