【问题标题】:grails/gorm multi column unique constraint violationgrails/gorm 多列唯一约束违规
【发布时间】:2013-10-02 15:44:35
【问题描述】:

我在下面添加了我的域。我试图在一个列上指定一个唯一约束,这将使该列基于另一列的值是唯一的,并且在父域中是唯一的。

public enum PostStatus {
    PUBLISHED,
    PENDING_REVIEW,
    DRAFT,
    TRASH
}

public enum PostType {
    INTRO,
    FUTURE,
    FAMILY
}


class Post {


    String content
    PostType postType
    PostStatus postStatus
    Date dateCreated
    Date lastUpdated
    static belongsTo = [basicProfile:BasicProfile]

    static constraints = {
        content(blank:true, nullable:true, maxSize:5000)
        postType(blank:false, nullable:false)
        postStatus(blank:false, nullable:false, unique:'postType') //status must be unique within each postType, and within the parent.
    }
    static mapping = {
        content sqlType:'text'
    }
}

class Profile {
    static hasMany = [
            post:Post
    ]
}

现在 postStatus 在 postType 中是唯一的,但它将唯一约束应用于 Post 表。因此,该表允许每个 postType 一个 postStatus,然后发生唯一约束违规。我需要的是每个 Profile 的每个 postType 都有一个唯一的 postStatus。

后表插入示例: 好记录#1: 个人资料 ID:1 post_status:草稿 post_type:介绍

良好记录#2: 个人资料 ID:1 post_status:已发布 post_type:介绍

良好记录#3: 个人资料 ID:1 post_status:草稿 post_type: 未来

错误记录 #4,违反了记录 1 的唯一约束,即使它用于不同的配置文件 ID。 个人资料 ID:2 post_status:草稿 post_type:介绍

帖子属于个人资料,那么我将如何定义约束以使其在每个个人资料中都是唯一的?本质上,我试图获得一个复合唯一键:

profile.id + postType + postStatus

【问题讨论】:

    标签: grails grails-orm


    【解决方案1】:

    您是否尝试过http://grails.org/doc/latest/ref/Constraints/unique.html 中描述的最后一个示例?

    例如:postStatus(blank:false, nullable:false, unique:['postType', 'basicProfile'])

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 2022-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多