grails - using multiple belongsTo, but only one at

2019-03-31 04:26发布

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.

标签: grails gorm
1条回答
劳资没心,怎么记你
2楼-- · 2019-03-31 05:17

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)

    } 
查看更多
登录 后发表回答