我有两个表: Books 和 Articles 之间存在多对多关系。连接表是 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
},
});
}
和模型/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});
但我无法获得书籍文章
我怎么才能得到它 ??
原文由 Anuj 发布,翻译遵循 CC BY-SA 4.0 许可协议
Sequelize 协会备忘单
为 Sequelize v2/3/4/5 更新
一般来说,我认为问题在于我们对创建什么表以及关联获得什么方法感到困惑。
TLDR;
O:O
O:M
N:M
关联为您提供 2 个功能:(1) 急切加载和 (2) DAO 方法:
1. 包括(急切加载)
2. hasOne()、hasMany()和belongsTo()/belongsToMany()获得的方法
关联提供数据访问对象 (DAO) 方法:
有一个():
在设置
Parent.hasOne(Child)
时,可用于parent
DAO 实例的方法:有很多():
在设置
Parent.hasMany(Child)
时,可用于parent
DAO 实例的方法:属于()/属于多:
在设置
Child.belongsTo(Parent)
时,可用于child
DAO 实例的方法:你也可以有多个关系
亲生父母/孩子
寄养父母/儿童
以上将创建
Parent_Child
交叉表,带有NaturalId
和FosterId
。