Mysql 在grails中查询两个表
我的grails项目中有两个域类。第一个是用户,第二个是联系人。用户与contact类有一对多关系,即一个用户有多个联系人。用户类是这样的Mysql 在grails中查询两个表,mysql,grails,gorm,Mysql,Grails,Gorm,我的grails项目中有两个域类。第一个是用户,第二个是联系人。用户与contact类有一对多关系,即一个用户有多个联系人。用户类是这样的 package contacts class User { String name String email String password static constraints = { name(nullable: false) email(nullable: false,email: t
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]
}
接触类是这样的
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作为来自user表的外键,user表中称为id。现在我想检索某个特定用户的所有联系人。我想知道怎么做。我尝试了不同的动态查询方法,但失败了。有人能帮我解决这个问题吗?只要你有用户对象,那么它就很简单:
def contacts = user.contacts
如果将用户标识传递给某个服务以检索它们,您可以执行以下操作:
def getUserContacts(Long userId) {
def user = User.load(userId)
def contacts = Contact.findAllByUser(user)
}
只要您拥有用户对象,它就非常简单:
def contacts = user.contacts
如果将用户标识传递给某个服务以检索它们,您可以执行以下操作:
def getUserContacts(Long userId) {
def user = User.load(userId)
def contacts = Contact.findAllByUser(user)
}
你的不同“方法”是什么?你问题的答案在于你的不同“方法”是什么?你问题的答案在于