【问题标题】:Constraint self referencing foreign key to limit nesting (SQL, Sequelize)约束自引用外键以限制嵌套(SQL、Sequelize)
【发布时间】:2018-10-22 02:44:52
【问题描述】:

我正在尝试制作一个包含此结构的表格:

<Comments>
id(PK, int)    comment_id(FK, int)    body(text)
1              null                   "This is a comment"
2              1                      "This is a nested comment"
3              2                      "This is a nested nested comment"

上面的例子代表了使用自引用表的优点——我想在一定程度上消除它。

评论的id: 3 引用comment_id=2 评论,而id=2 引用comment_id=1

我想将此嵌套引用限制为单个级别,并能够添加一个特定的约束,该约束检查并建立一个等于第一级嵌套的值。

为了更清楚,此时id=3 应该引用comment_id=2 而不是引用comment_id=1,如下所示:

<Comments>
id(PK, int)    comment_id(FK, int)    body(text)
1              null                   "This is a comment"
2              1                      "This is a nested comment"
3              1                      "This is a nested nested comment"

我想让后端在处理这种情况时尽可能不忙,只需在我的创建查询中提供comment_id=2 的引用,我希望它自动指向id=2 的引用comment_id=1 而不是 comment_id=2

除了我在 NodeJS 中使用 Sequelize 并能够限制后端路由中的数据之外,我想了解如何使用 sql(或 sequelize)来实现这一点,以保持数据完整性流线性。

【问题讨论】:

    标签: sql node.js sequelize.js sequelize-cli


    【解决方案1】:

    您可以通过拥有另一张桌子来做到这一点。如果您的 cmets 正在引用 something,那么您可以使用该表。否则:

    create table comments (
        commentId int primary key,
        . . .
    );
    
    create table commentLines (
        commentLineId int primary key,
        commentId int references comments(commentId),
        comment varchar(255)
    );
    

    【讨论】:

    • 这似乎合乎逻辑,我已经考虑过这个解决方案,但它是实现这一目标的唯一方法吗?因为我想保留自引用表的想法。
    • @moodseller 。 . .我认为这可以更好地表达您想要表达的数据模型。
    猜你喜欢
    • 2020-03-17
    • 1970-01-01
    • 2019-07-26
    • 1970-01-01
    • 2018-02-13
    • 1970-01-01
    • 1970-01-01
    • 2013-01-30
    • 1970-01-01
    相关资源
    最近更新 更多