【问题标题】:Querying two tables in grails查询grails中的两个表
【发布时间】:2016-08-12 04:21:04
【问题描述】:

我的 grails 项目中有两个域类。第一个是用户,第二个是联系人。用户与联系人类具有一对多的关系,即一个用户有多个联系人。用户类是这样的

package contacts

class User {
    String name
    String email
    String password

    static constraints = {
        name(nullable: false)
        email(nullable: false,email: true,blank: false )
        password(nullable: false,size: 6..8,blank: false,password:true)
    }
    static hasMany = [contacts: Contact]

    String toString(){
        return name
    }
}

而联系人类是这样的

package contacts

class Contact {
    String firstName
    String lastName
    String email
    String phone
    String address
    Date dateCreated

    static constraints = {

        firstName(nullable: false)
        lastName(nullable: true)
        email(nullable: false)
        phone(nullable: true)
        address(nullable: true)
        dateCreated()
    }
       static belongsTo = [user: User]

}

当我编译它时,它创建了两个名为 user 和 contact 的表,contact 表有 user_id 作为用户表的外键,在用户表中称为 id。现在我想检索某个特定用户的所有联系人。我想知道如何做到这一点。我尝试了不同的动态查询方法,但失败了。谁能帮我解决这个问题?

【问题讨论】:

  • 你有什么不同的“方法”?
  • 你的问题的答案在this post

标签: mysql grails grails-orm


【解决方案1】:

只要你有 User 对象,那么就这么简单:

def contacts = user.contacts

如果将 userId 传递给某个服务以检索它们,您可以这样做:

def getUserContacts(Long userId) {
  def user = User.load(userId)
  def contacts = Contact.findAllByUser(user)
}

【讨论】:

    猜你喜欢
    • 2013-04-26
    • 2020-07-23
    • 2017-06-08
    • 1970-01-01
    • 1970-01-01
    • 2013-10-13
    • 1970-01-01
    • 1970-01-01
    • 2015-10-14
    相关资源
    最近更新 更多