grails - Grails GORM约束

标签 grails constraints gorm

给定以下两个域:

class Follows {
    User followee
    ...
    static belongsTo = [follower: User]
}

class User {
    String name
    String lastName
    ...
    static hasMany = [ follows: Follows ]
    static mappedBy = [ follows: 'follower' ]
}

这将创建下表:
+------+-------------+-------------+
|  id  | follower_id | followee_id |
+------+-------------+-------------+
| 1    | 1           | 3           |
| 2    | 3           | 2           |
| 3    | 2           | 1           |
+------+-------------+-------------+

有没有办法通过约束来防止追随者-被追随者重复?我正在尝试阻止两个方向,例如,如果用户ID 1已经在用户ID 3之后,则用户ID 3应该不能跟随用户ID 1。

换句话说,这就是我要防止的事情:
+------+-------------+-------------+
|  id  | follower_id | followee_id |
+------+-------------+-------------+
| 1    | 1           | 3           |
| 2    | 3           | 1           |
+------+-------------+-------------+

我知道我可以在插入之前查询数据库,以检查用户1是否跟随3(或者反之),如果为true,则取消插入,但是我试图避免在每次跟随操作时两次访问数据库。

欢呼,感谢您的所有答复!

最佳答案

不,没有现有的约束来处理这种情况。您可以创建自己的约束,但是必须查询数据库,所以没有意义。

但是,如果您向Follows添加一个新属性,该属性包含适用于以下两个方向的唯一值,则可以使用唯一约束。

class Follows {
    User followee
    ...
    Integer someUniqueProperty

    static belongsTo = [follower: User]

    static constraints = {
        someUniqueProperty unique: true
    }

    def beforeInsert() {
        someUniqueProperty = calculateUniqueProperty()
    }

    def beforeUpdate() {
        someUniqueProperty = calculateUniqueProperty()
    }

    private Integer calculateUniqueProperty() {
       [follower.id, followee.id].sort().hashCode()
    }
}

在上面的示例中,someUniquePropertyFollows的所有实例中必须唯一。在插入/更新实例之前,先将followerfollowee始终以相同的顺序放在列表中,然后获取哈希码,然后设置其值。这是基于以下事实:[1, 3].hashCode() == [3, 1].sort().hashCode()
简而言之,添加唯一属性可使数据库强制执行所需的约束。

关于grails - Grails GORM约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33587937/

相关文章:

mysql - 防止 MySQL 中的特定更新

grails - 关联中的GORM和复合键

grails - GORM-表的层次结构-如何在域类中更改表名

eclipse - Groovy Grails Tools Suit (GGTS) Maven 插件

hibernate - Grails 抛出表 "xxx"未找到

spring - Spring Security:REST API需要哪个过滤器

hibernate - 限制不同查询返回的结果

Grails Spring 安全用户界面

swift - 编程约束未按预期工作

c# - 使用类型约束重载方法