如何在Grails中实现自引用关系

如何在Grails中实现自引用关系

本文介绍了如何在Grails中实现自引用关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下用户类:

class User {

  String name

  static hasMany = [friends: User]
}

我希望用户可以有很多朋友,这些朋友是用户域类的实例.

I want that a User can have many friends which are instances of the user domain class.

我如何实现用户的朋友关系?

How do I have to implement the friend relationship of a user?

推荐答案

1.您如何定义亲戚关系

     class User  {
        static hasMany   = [ friends: User ]
        static mappedBy  = [ friends: 'friends' ] //this how you refer to it using GORM as well as Database
         String name

        String toString() {
            name
        }
      def static constrains () {
          name(nullable:false,required:true)

       }
     def static mapping={
     / / further database custom mappings ,like custom ID field/generation
     }
    }

2.如何保存数据:

def init = {servletContext->

if(User?.list()==null) { // you need to import User class :)
def user = new User(name:"danielad")
def friends= new User(name:'confile')
def friends2=new User(name:'stackoverflow.com')
user.addToFriends(friends)
user.addToFriends(friends2)
user.save(flash:true)
}
}

3#.您的问题在此堆栈溢出链接上重复:维护自我Grails域对象中的引用多对多关系

3# . Your question is repeated on this stack overflow link :Maintaining both sides of self-referential many-to-many relationship in Grails domain object

这篇关于如何在Grails中实现自引用关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 08:29