带有外键的Grails findBy查询
Grails findBy query with foreign key
我正在尝试通过调用 User
对象上的 getProfiePicture()
方法从数据库中获取用户个人资料图片。
方法调用 来自视图:
<p>${user.getProfilePicture()}</p>
User.groovy 域 class:
class Picture {
User user
String url
boolean profile = false
boolean verified = true
static belongsTo = [user: User]
static constraints = {
}
}
Picture.groovy 域 class:
class User {
static hasMany = [pictures: Picture]
String uid = UUID.randomUUID().toString()
String username
String password
String getProfilePicture() {
log.debug("ID: " + id)
log.debug("UID: " + uid)
log.debug("Pictures: " + pictures)
return Picture.findByUserIdAndProfile(id, true)
}
}
图片table:
问题
我在尝试获取个人资料照片时遇到此错误:
Class
org.codehaus.groovy.grails.exceptions.InvalidPropertyException
Message
No property found for name [userId] for class [class foo.Picture]
我做错了什么?
我正在使用:
- Grails 2.4.4
您可以按如下方式实施 getProfilePicture
:
String getProfilePicture() {
Picture.where { user == this && profile == true}.first().url
}
或者,您可以使用动态 Finder(如评论中所示)。顺便说一句:Picture Class 不需要两次创建用户属性。 static belongsTo = [user: User]
够了。
您的 User
域 class 中的 getProfilePicture()
方法应该 return 以下内容:
Picture.findByUserAndProfile(this, true)
您收到该错误的原因是因为您试图通过 userId
查找一个 Picture
实例,一个不存在的字段。
我正在尝试通过调用 User
对象上的 getProfiePicture()
方法从数据库中获取用户个人资料图片。
方法调用 来自视图:
<p>${user.getProfilePicture()}</p>
User.groovy 域 class:
class Picture {
User user
String url
boolean profile = false
boolean verified = true
static belongsTo = [user: User]
static constraints = {
}
}
Picture.groovy 域 class:
class User {
static hasMany = [pictures: Picture]
String uid = UUID.randomUUID().toString()
String username
String password
String getProfilePicture() {
log.debug("ID: " + id)
log.debug("UID: " + uid)
log.debug("Pictures: " + pictures)
return Picture.findByUserIdAndProfile(id, true)
}
}
图片table:
问题
我在尝试获取个人资料照片时遇到此错误:
Class
org.codehaus.groovy.grails.exceptions.InvalidPropertyException
Message
No property found for name [userId] for class [class foo.Picture]
我做错了什么?
我正在使用:
- Grails 2.4.4
您可以按如下方式实施 getProfilePicture
:
String getProfilePicture() {
Picture.where { user == this && profile == true}.first().url
}
或者,您可以使用动态 Finder(如评论中所示)。顺便说一句:Picture Class 不需要两次创建用户属性。 static belongsTo = [user: User]
够了。
您的 User
域 class 中的 getProfilePicture()
方法应该 return 以下内容:
Picture.findByUserAndProfile(this, true)
您收到该错误的原因是因为您试图通过 userId
查找一个 Picture
实例,一个不存在的字段。