问题
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