grails - using multiple belongsTo, but only one at a time

六眼飞鱼酱① 提交于 2019-12-21 05:22:29

问题


If I want to use a domain class, e.g. MoneyTransaction, for two entirely different purposes, i.e.:

1) when a customer places an order

2) when a member gets paid

such that I have something like:

class Order {
   static hasMany = [transactions: MoneyTransaction]
}

class Member {
   static hasMany = [payments: MoneyTransaction]
}

and

class MoneyTransaction {
   static belongsTo = [order: Order, member: Member]
   static constraints = {
      order(nullable: true)
      member(nullable: true)
   }
}

and then in essence only use one belongsTo/association at a time, is this pretty "standard" usage, or do I need to switch this modeling? Right now MoneyTransaction has both credit card and ACH payment capabilities, as both apply for orders. For payments, just the ACH portion will be used.


回答1:


The domain class definitions that you have posted seem correct based on your requirements. One modification that I'd make here would be to add a custom validator to make sure that both order and member are not null at the same time.

    static constraints = {

    order(nullable: true, validator: {field, inst -> inst.member || field})
    member(nullable: true)

    } 


来源:https://stackoverflow.com/questions/8638940/grails-using-multiple-belongsto-but-only-one-at-a-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!