【问题标题】:Grails findBy query with foreign keyGrails findBy 外键查询
【发布时间】:2015-05-09 04:09:31
【问题描述】:

我正在尝试通过在 User 对象上调用 getProfiePicture() 方法从数据库中获取用户个人资料图片。

方法调用来自视图:

<p>${user.getProfilePicture()}</p>

User.groovy 域类:

class Picture {

  User user
  String url
  boolean profile = false
  boolean verified = true
  
  static belongsTo = [user: User]

  static constraints = {
  }
}

Picture.groovy 域类:

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)
  }
  
}

图片表:

问题

我在尝试获取个人资料图片时收到此错误:

Class
org.codehaus.groovy.grails.exceptions.InvalidPropertyException
Message
No property found for name [userId] for class [class foo.Picture]

我做错了什么?

我正在使用:

  • Grails 2.4.4

【问题讨论】:

  • Picture 没有属性userId 它有一个属性user 所以你可以使用findByUserAndProfile(user, true)
  • @JoshuaMoore 是的,做到了!
  • 是的,我知道会的;)

标签: grails groovy grails-orm


【解决方案1】:

User 域类中的 getProfilePicture() 方法应返回以下内容:

Picture.findByUserAndProfile(this, true)

您收到该错误的原因是您试图通过userId 查找Picture 实例,该字段不存在。

【讨论】:

    【解决方案2】:

    您可以如下实现getProfilePicture

    String getProfilePicture() {
        Picture.where { user == this && profile == true}.first().url
    }
    

    您也可以使用动态查找器(如 cmets 中所示)。顺便说一句:图片类不需要创建两次用户属性。 static belongsTo = [user: User] 就够了。

    【讨论】:

    • 我按照你的建议删除了belongsTo,一切都很好,但我去了 JoshuaMoore 的回答。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2018-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    • 2011-02-01
    • 2018-09-01
    相关资源
    最近更新 更多