【问题标题】:grails adding a domain object to another domain without the domains having a relationshipgrails将域对象添加到另一个域而域没有关系
【发布时间】:2016-06-26 08:47:22
【问题描述】:

美好的一天。我是 grails 和 groovy 的新手,我想做的是将域对象(在我的情况下是专辑对象)添加到不同的域(购物车)。当用户在查看专辑时单击“添加到购物车”链接时,HomeController 的“购买”操作应该会创建专辑的副本并将其放入购物车域,但我不知道该怎么做.这是我得到的。

class HomeController{
   def index(){ 
      //displays a list of albums and a 'add to cart' link at each album in the list
   }

   def buy(){
      //Here's where the code should go.
      redirect(controller: "home", action: "index")   
   }

}

【问题讨论】:

    标签: grails grails-orm multiple-domains


    【解决方案1】:

    我认为在尝试视图/控制器之前,您需要更多地考虑您的 domainClasses:

    你有一个域对象(在我的例子中是专辑对象)到另一个域(购物车)

    领域类:

    class User {
        String name
        static hasMany = [orders:Orders]
    }
    
    Class Album {
        String name
    }
    
    class Order {
        User user
        Album album
    }
    

    视图:显示此内容的控制器操作:

    <!-- by defining user.id and album.id when grails receives the .id it binds that id to the actual object so --!>
    <!-- User user = params.user  // is the user object bound to user.id --!>
    <g:form action="save" controller="myController">
        <g:hidden name="user.id" value="1"/>
        <g:select name="album.id" from="${mypackage.Album.list()}" optionKey="id" optionValue="name"/>
        <g:submitButton name="save">
    </g:form>
    

    控制器接收该保存操作 - 保存功能实际上应该被接管到事务服务 = 这只是为了向您展示非常基本的内容:

    package mypackage
    
    class MyController {
    
        def save() { 
    
            Order order= new Order(params)
            order.save()
    
            // 
            //User user=User.get(params.user.id) 
            User user=params.user
    
            user.addToOrders(order)
            user.save()
    
            render "album added to order class and then order added to users class"
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-03-26
      • 2011-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-11
      相关资源
      最近更新 更多