0

私の grails プロジェクトには 2 つのドメイン クラスがあります。1 つ目はユーザー、2 つ目は連絡先です。ユーザーは連絡先クラスと 1 対多の関係にあります。つまり、1 人のユーザーが多くの連絡先を持っています。ユーザークラスはこのようなものです

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 という名前の 2 つのテーブルが作成されます。contact テーブルには、user テーブルで id と呼ばれる user テーブルからの外部キーとして user_id があります。今、特定のユーザーのすべての連絡先を取得したいと考えています。私はこれを行う方法を疑問に思っています。動的クエリのさまざまなアプローチを試しましたが、失敗しました。誰でもこれを解決するのを手伝ってもらえますか?

4

1 に答える 1

3

User オブジェクトがあれば、次のように簡単です。

def contacts = user.contacts

userId がサービスに渡されて取得されている場合は、次のことができます。

def getUserContacts(Long userId) {
  def user = User.load(userId)
  def contacts = Contact.findAllByUser(user)
}
于 2013-09-10T22:45:56.527 に答える