【问题标题】:GORM Querying multiple collectionsGORM 查询多个集合
【发布时间】:2014-08-09 09:43:45
【问题描述】:

我正在使用 Grails 和 MongoDB。我有两个域类 User 和 AddWebsite。一个用户有很多网站,每个网站都属于一个用户。 领域类如下:

class AddWebsite{
String website
User user
static belongsTo = [user: User]
static constraints = {
    website url:true
    user nullable:true
}
}

Other domain类如下:

class User {
    String login
    String password
    static hasMany = [
        addWebsites: AddWebsite
    ]
    static mapping = {
        addWebsites cascade:"all-delete-orphan"
      }
    static constraints = {
        }
    }

我需要根据当前登录的用户查询 AddWebsite 表并获取该特定用户的网站。任何人都可以提出任何方法吗?

【问题讨论】:

    标签: mongodb grails join collections grails-orm


    【解决方案1】:

    我使用了这种方法。可能不是最有效的,但它确实有效。

    def showWebsites(){
        def p = User.findByLogin(session["user"].login)
        def websites = AddWebsite.findAllByUser(p['_id'])
        [websitesList: websites] 
    }
    

    在我的 GSP 中,我有:

    <g:select name="websiteSelection" from="${websitesList.website} " />
    

    【讨论】:

      【解决方案2】:
      You need to create a createCriteria List as follow
      
      def c = AddWebsite.createCriteria()
      def results = c.list {
      
                 //find the user based on the relationship
                   user {
      
                         ideq(userobj?.id.toLong())
      
                    }
      
                //you can user projection here if u need a single value
      
          }
      

      【讨论】:

        【解决方案3】:

        我没有使用过 MongoDB,但由于 GORM 支持它,我假设一个示例查询可以满足您的需求:

        AddWebsite.findAllByUser(userObj)

        如果您只是想要网站字符串,那么这应该可以:

        def userWebsites = AddWebsite.findAllByUser(userObj)*.website

        其中 userWebsites 将是 List&lt;String&gt;

        请参阅http://grails.org/doc/latest/ref/Domain%20Classes/findAllBy.html 了解更多信息。

        顺便说一句,您的 AddWebsite 类中不需要“用户用户”,因为您已在 belongsTo 中命名为“用户”。

        【讨论】:

        • 感谢您的链接。它真的很有用。
        猜你喜欢
        • 2019-05-09
        • 2019-12-28
        • 1970-01-01
        • 1970-01-01
        • 2012-05-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-01
        相关资源
        最近更新 更多