我们如何在sequelize中设置关系树

问题描述 投票:0回答:1

我的问题在这里:

`// Define Associations
`User.hasMany(Post, { foreignKey: "userId" }); // A User can have many Posts
Post.belongsTo(User, { foreignKey: "userId" }); // A Post belongs to a User

Comment.belongsTo(User, { foreignKey: "userId" }); // A Comment belongs to a User
Comment.belongsTo(Post, { foreignKey: "postId" }); // A Comment belongs to a Post``

作为一个用户有很多帖子,并且一个帖子有很多评论,那么为什么在这段代码中没有指定帖子有很多评论呢?请详细解释一下,因为我两天内有一个项目,这让我很困惑。

sequelize.js
1个回答
0
投票

如果您有外键,那么您可以链接

two
表(显然),对吧?您根据这个 FK 定义什么关联完全取决于您以及您的应用程序需要获得什么。

回到您的示例:如果您不需要获取某个帖子的所有评论,那么您可以根本不定义

Post.hasMany(Comment, ...
关联。

您所展示的关联可用于获得:

  1. 用户/用户及其帖子
  2. 与链接用户发布的帖子
  3. 对链接帖子和/或链接用户发表评论

如果您想获取带有评论的帖子,那么您需要定义:

Post.hasMany(Comment, { foreignKey: "postId" }); // Comments of a post
定义关联时,您只需提示 Sequelize 模型如何链接,它可能与数据库中的真实外键无关,或者只能反映数据库中表关系的子集。通常,您为每个 FK 定义两个关联:

hasMany/belongsTo

hasOne/belongsTo
 或两个 
belongsToMany
,但有时您只是不需要其中的一些关联,这可能会导致每个 FK 仅有一个关联。

© www.soinside.com 2019 - 2024. All rights reserved.