我有一个应用程序,其中所有者对象可以有许多帐户对象,而帐户对象可以有许多所有者对象。我想过用多对多的关系对它进行建模,但后来我意识到我可能还需要创建帐户对象,其中所有者无法立即确定,或者可能在将来创建帐户后创建。因此,我不相信我可以使用Grails多对多关系(我认为)。所以,我只是在Owner类中有一个属性,它是一个Account ID列表(这将是Owner's Accounts引用)和Account类中的一个属性,它是Owner ids的列表(这将是Account的业主参考)。有更好的想法吗?我觉得这太老式了,类似于C ++指针的做法。
答案 0 :(得分:1)
您可以创建第三个域来解决此关系
class Owner{
...
Set<Object> getObjects() {
OwnerObject.findAllByOwner(this).collect { it.object } as Set // or replace with optimized criteria
}
...
}
class Object{
...
Set<Owner> getOwners() {
OwnerObject.findAllByObject(this).collect { it.owner } as Set // or replace with optimized criteria
}
...
}
class OwnerObject implements Serializable {
Owner owner
Object object
boolean equals(other) {
if (!(other instanceof OwnerObject)) {
return false
}
other.owner?.id == owner?.id && other.object?.id == object?.id
}
static OwnerObject get(long ownerId, long objectId) {
find 'from OwnerObject where owner.id=:ownerId and object.id=:objectId',
[ownerId: ownerId, objectId: objectId]
}
static OwnerObject create(Owner owner, Object object, boolean flush = false) {
new OwnerObject(owner: owner, object: object).save(flush: flush, insert: true)
}
static boolean remove(Owner owner, Object object, boolean flush = false) {
OwnerObject instance = OwnerObject.findByOwnerAndObject(owner, object)
if (!instance) {
return false
}
instance.delete(flush: flush)
true
}
static void removeAll(Owner owner) {
executeUpdate 'DELETE FROM OwnerObject WHERE owner=:owner', [owner: owner]
}
static void removeAll(Object Object) {
executeUpdate 'DELETE FROM OwnerObject WHERE object=:object', [object: object]
}
static mapping = {
id composite: ['object', 'owner']
version false
}
}
答案 1 :(得分:1)