如何在sequelize中实现多对多关联

2023-11-22

我有两个表:书籍和文章,它们之间具有多对多关系。 连接表是 BookArticles。

模型/books.js

module.exports = function(sequelize, DataTypes) {
  return Food = sequelize.define("Book", {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      allowNull: false,
      autoIncrement: true,
      unique: true
    }
  });
}

模型/articles.js

module.exports = function(sequelize, DataTypes) {
  return Food = sequelize.define("Article", {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      allowNull: false,
      autoIncrement: true,
      unique: true
    }
  });
}

模型/bookArticles.js

module.exports = function(sequelize, DataTypes) {
  return Food = sequelize.define("BookArticles", {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      allowNull: false,
      autoIncrement: true,
      unique: true
    },
   bookId: {
      type: DataTypes.INTEGER,
      references: 'Book',
      referencesKey: 'id',
      allowNull: false
    },
    ArticleId: {
      type: DataTypes.INTEGER,
      references: 'Article',
      referencesKey: 'id',
      allowNull: false
    },
  });
}

和 models/index.js

m.BookArticles.belongsTo(m.Book);
m.Book.hasMany(m.Article, {through: m.BookArticles});


m.BookArticles.belongsTo(m.Article);
m.Article.hasMany(m.Books, {through: m.BookArticles});

但我无法获取书籍文章

我怎么才能得到它 ??


Sequelize 协会备忘单

更新了 Sequelize v2/3/4/5

一般来说,我认为问题在于我们对创建哪些表以及通过关联获得哪些方法感到困惑。

注意:定义foreignKey或交叉表名称是可选的。 Sequelize 会自动创建它,但定义它允许编码人员读取模型并找出外键/交叉表名称,而不是猜测或需要访问数据库。

TLDR;

O:O

// foreign key has to be defined on both sides.
Parent.hasOne(Child, {foreignKey: 'Parent_parentId'})
// "Parent_parentId" column will exist in the "belongsTo" table.
Child.belongsTo(Parent, {foreignKey: 'Parent_parentId'})

O:M

Parent.hasMany(Child, {foreignKey: 'Parent_parentId'})
Child.belongsTo(Parent, {foreignKey: 'Parent_parentId'})

N:M

Parent.belongsToMany(
    Child, 
    {
        // this can be string (model name) or a Sequelize Model Object Class
        // through is compulsory since v2
        through: 'Parent_Child',

        // GOTCHA
        // note that this is the Parent's Id, not Child. 
        foreignKey: 'Parent_parentId'
    }
)

/*
The above reads:
"Parents" belongs to many "Children", and is recorded in the "Parent_child" table, using "Parents"'s ID.
*/

Child.belongsToMany(
    Parent, 
    {
        through: 'Parent_Child',

        // GOTCHA
        // note that this is the Child's Id, not Parent.
        foreignKey: 'Child_childId'
    }
)

为什么是详细的“Parent_parentId”而不仅仅是“parentId”?这是为了表明它是属于“Parent”的外键。在大多数情况下,使用更简洁的“parentId”就可以了。*

关联为您提供 2 种功能:(1) 预加载和 (2) DAO 方法:

1. 包含(预加载)

DB.Parent.findOne({ 
    where: { id: 1 },
    include: [ DB.Child ]
}).then(parent => {

    // you should get `parent.Child` as an array of children. 

})

2. hasOne()、hasMany()和belongsTo()/belongsToMany()获得的方法

关联提供数据访问对象 (DAO) 方法:

hasOne():

在设置一个Parent.hasOne(Child),可用的方法parentDAO 实例:

DB.Parent.findOne({ where: { id: 1 } }).then(parent => {

    // `parent` is the DAO
    // you can use any of the methods below:
    parent.getChild
    parent.setChild
    parent.addChild
    parent.createChild
    parent.removeChild
    parent.hasChild

})
hasMany():

在设置一个Parent.hasMany(Child),可用的方法parentDAO 实例:

parent.getChildren,
parent.setChildren,
parent.addChild,
parent.addChildren,
parent.createChild,
parent.removeChild,
parent.hasChild,
parent.hasChildren,
belongsTo()/belongsToMany:

在设置一个Child.belongsTo(Parent),可用的方法childDAO 实例:

child.getParent,
child.setParent,
child.createParent,

//belongsToMany
child.getParents,
child.setParents,
child.createParents,

您还可以拥有多种关系

Natural Parents/Children
// a parent can have many children
Parent.belongsToMany(Child, {
    as: 'Natural',
    through: 'Parent_Child',
    foreignKey: 'Parent_parentId'
})
// a child must at least have 2 parents (natural mother and father)
Child.belongsToMany(Parent, {
    as: 'Natural',
    through: 'Parent_Child',
    foreignKey: 'Child_childId'
})
Foster Parents/Children
Parent.belongsToMany(Child, {
    as: 'Foster',
    through: 'Parent_Child',
    foreignKey: 'Parent_parentId'
})

Child.belongsToMany(Parent, {
    as: 'Foster',
    through: 'Parent_Child',
    foreignKey: 'Child_childId'
});

以上将创建Parent_Child交叉表,有NaturalId and FosterId.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在sequelize中实现多对多关联 的相关文章

随机推荐

  • Autofac - 生命周期和模块

    问题 摘要 给定一个注册依赖项 X 的模块 依赖项 X 在 MVC3 应用程序中具有不同的生命周期 每个 HttpRequest 的生命周期 然后在控制台应用程序中 每个具有名称的生命周期范围的依赖项 在哪里或如何指定依赖项 X 的生命周期
  • 使用 XSD 正确验证 XML 文档

    作为一名具有丰富 XML 使用和生成经验的开发人员 我以前从未真正与模式进行过交互 这对我来说是第一次真正发生 我遇到过一个 功能 我认为它更像是一个有详细记录的错误 使用 XDocument Validate 时 似乎在某些情况下 如果文
  • OnApplicationFocus() 和 OnApplicationPause() 有什么区别?

    说到移动设备 这两种方法有什么区别 如果我按主页键 两者都会被调用 有没有一种情况 一个被调用 另一个不被调用 由于这个 UnityAnswer 是第一个 如果不是第一个 在搜索 OnApplicationFocus Pause 和 iOS
  • 谷歌 aspnet mvc5 上的 AuthenticationManager.GetExternalLoginInfoAsync() 返回 null [重复]

    这个问题在这里已经有答案了 我使用默认的 Visual Studio 2015 模板和 Google 身份验证开发了 ASPNET MVC 5 应用程序 在开发环境中一切正常 但在外部身份验证后的实际调用中AuthenticationMan
  • Python 2.6 通过队列/管道/等发送连接对象

    Given 这个错误 Python 问题 4892 这会导致以下错误 gt gt gt import multiprocessing gt gt gt multiprocessing allow connection pickling gt
  • 多个参数与选项对象

    当创建具有多个参数的 JavaScript 函数时 我总是面临这样的选择 传递参数列表还是传递选项对象 例如 我正在编写一个函数来将 nodeList 映射到数组 function map nodeList callback thisObj
  • 如何替换除第一个之外的所有出现的情况?

    如何替换字符串中除第一个单词之外的所有重复单词 就是这些字符串 s cat WORD dog WORD mouse WORD s1 cat1 WORD dog1 WORD 将被替换为 s cat WORD dog REPLACED mous
  • IE7 iframe 空白页

    我正在处理一个有 iframe 的网页 并且我正在 iframe 中加载外部网站 该页面在 IE6 FF 等中工作正常 但在 IE7 中我看到的只是一个空白页面 我发现这是由于IE7中的网络钓鱼过滤器造成的 网络钓鱼过滤器将无法检查 ifr
  • 非常有用的VB6源代码[关闭]

    Closed 此问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 目前不接受答案 这不是一个问题 但我想我应该启动一个线程 其中可以放置指向特别有用 且广泛适用 的 vb6 代码的链接 我的选择是由一个名叫 John Korejw
  • 使用 tsconfig.json 忽略 *.js 和 *.jsx 文件

    这是我们尝试过的 compilerOptions target esnext moduleResolution node allowJs true jsx react include src exclude src js src jsx 当
  • 找到加载特定类的ClassLoader

    有没有办法确定哪个类加载器加载特定的类 或者更具体地说 从加载特定类的位置 我遇到了加载旧数据库驱动程序类的情况 我想找到加载旧驱动程序的文件 我最初的方法是在 ClassLoader loadClass 方法上设置一个调试点 并在类加载后
  • 在 Spring Security 中根据某种所有权设置用户角色

    在我基于 Spring 的应用程序中 我目前拥有 ADMIN 和 USER 等基本角色 是否可以定义一个用户角色 例如 PHOTO UPLOADER 它继承自 USER 但还添加了检查发出调用的用户是否实际上是照片的所有者 我厌倦了写同样的
  • 如何实现.NET MAUI本地化

    我无法找到任何有关为 MAUI 应用程序实施本地化的指导 我已经阅读了一些有关本地化 Xamarin 应用程序的信息 但即使经过广泛的网络搜索 也无法将其转发到 MAUI 谁能给我指出我可能错过的参考资料 试试这个 创建标准资源 添加新项目
  • 检测 GitHub 提交的 IP 地址

    我是一些公司 github 存储库的所有者 最近 我们一直怀疑一名开发人员可能通过借用的 github 身份寻求外包帮助 许多凌晨 4 点批量提交 github com 上有没有办法确定提交者的源 IP 地址 在流量页面上 我可以根据独特克
  • 如何修复 EF Core 迁移“证书链由不受信任的机构颁发”

    连接字符串 Data Source
  • 如何最好地告诉 CMake 在哪里可以找到 dll

    我有一个简单的项目结构 源自令人惊叹的教程 https rix0r nl blog 2015 08 13 cmake guide 它看起来如下 src CMakeLists txt mylib include mylib mylibclas
  • 从 Android 应用程序打开本机浏览器

    我有一部安装了多个浏览器的 Android 手机 我可能会或可能不会将浏览器设置为默认值 所以 我的问题是 从我的应用程序中 如何仅在NATIVE安卓浏览器 有没有办法知道是否有浏览器设置为默认浏览器 从我的应用程序中 如何仅在 NATIV
  • 这是使用 History.js 的正确方法吗?

    我能够使用三个链接来组合一个简化的完整 History js 示例 从整个页面加载内容片段 而无需更新页面 同时更新浏览器历史记录 这是相关的代码片段 完整的工作示例在这里http jsfiddle net PT7qx show a hre
  • .NET MAUI 应用程序上 iOS 上覆盖表单元素的键盘

    我正在将我的 Xamarin 应用程序转换为 NET MAUI 看起来像
  • 如何在sequelize中实现多对多关联

    我有两个表 书籍和文章 它们之间具有多对多关系 连接表是 BookArticles 模型 books js module exports function sequelize DataTypes return Food sequelize