node.js - 如何在sequelize中实现多对多关联

标签 node.js express sequelize.js

我有两个表:Books 和 Articles,它们之间存在多对多关系。 连接表是 BookArticles。

models/books.js

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

models/articles.js

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

models/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 Association 备忘单

为 Sequelize v2/3/4/5 更新

总的来说,我认为问题在于我们对创建什么表以及关联获得什么方法感到困惑。

Note: Defining foreignKey or cross table name are optional. Sequelize automatically creates it, but defining it allows coders to read the models and find out what the foreign keys/cross table names are, instead of guessing or needing to access the database.

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'
    }
)

Why the verbose "Parent_parentId" and not just "parentId"? This is to make it obvious that it's a foreign key that belonged to "Parent". In most cases it's okay to just use the more succinct "parentId".*

Associations 为您提供 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) 方法:

有一个():

在设置 Parent.hasOne(Child) 时,parent DAO 实例可用的方法:

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

})
有很多():

在设置 Parent.hasMany(Child) 时,parent DAO 实例可用的方法:

parent.getChildren,
parent.setChildren,
parent.addChild,
parent.addChildren,
parent.createChild,
parent.removeChild,
parent.hasChild,
parent.hasChildren,
属于()/属于多:

在设置 Child.belongsTo(Parent) 时,child DAO 实例可用的方法:

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

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

你也可以有多个关系

亲生 parent / child
// 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'
})
寄养 parent / child
Parent.belongsToMany(Child, {
    as: 'Foster',
    through: 'Parent_Child',
    foreignKey: 'Parent_parentId'
})

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

上面将创建 Parent_Child 交叉表,带有 NaturalIdFosterId

关于node.js - 如何在sequelize中实现多对多关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22958683/

相关文章:

node.js - 在 Node 中使用redis获取哈希键的所有字段和值

node.js - 在不重复的情况下重新调整 NEO4J 中的复杂树状结构

node.js - MEAN Stack : Very specific web requests to generic model methods, 或具有非常具体模型方法的通用 Web 请求?

node.js - 引用错误 : DATABASE_URL is not defined when trying to connect to heroku postgres db using Sequelize

postgresql - 如何使用 Feather-Sequelize 连接两列进行搜索?

javascript - 没有返回有效的 JSON?

node.js - Cordova 安装错误 : path issue (? ) - 错误代码 ENOENT

node.js - 如何将变量传递到应该是属性的 MongoDB 查询中

node.js - 如何使用 express 4.x 获取 ip 客户端

javascript - 返回 Sequelize 中行的自定义值?