将两个相同的外键作为序列中的两个不同字段添加到单个模型 [英] Adding two of the same foreighn keys to a single model as two different fields in sequelize
问题描述
我正在使用续集为项目构建数据库结构。我为该项目创建了friends表。是否可以使用sequelize将用户外键设置为朋友数据库表中的两个不同字段(Friender,Friended)。我知道我可以使用 Friend.hasOne(User)User.hasMany(Friend)
创建外键,但这只是将一个字段分配为外键。我想拥有两个与两个不同字段具有相同模型的外键。
I am building the database structure for a project using sequelize. I am created the friends table for the project. Is it possible to set a user foreign key to two different fields (friender, friended) in the friend database table using sequelize. I know that I can create a foreign key using Friend.hasOne(User) User.hasMany(Friend)
but that just assigns one field as a foreign key. I want to have two foreign keys that are the same model as two different fields.
到目前为止,这是我的续集数据库模型(朋友):
This is what I have so far for my sequelize database model (Friend):
const seq = require('sequelize');
const database = require('../index');
const Friend = database.define(
"friend",
{
id:{
type:seq.INTEGER,
primaryKey:true,
autoIncrement:true
},
favorite:{
type:seq.STRING,
null:true,
validate:{
isUrl: true,
}
},
},{
createdAt: Sequelize.DATE,
updatedAt: Sequelize.DATE,
},
database.sync()
.then(() => {
console.log("Profile table is synced")
})
.catch((error) => {
console.log("caught error with Profile: " + error)
})
);
Friend.hasOne(User)
User.hasMany(Friends)
我希望 Friend.friender
是 User
的外键。 $ c> Friend.friended 也是 User
不的快捷键确定如何执行此操作...
Not sure how to do this...
推荐答案
通过数据透视表称为多对多关系。
It's called many to many relation through pivot table.
添加少量字段进行建模并通过它定义多对多关系:
Add few fields to model and define many to many relation through it:
const seq = require('sequelize');
const database = require('../index');
const Friend = database.define(
"friends",
{
id:{
type:seq.INTEGER,
primaryKey:true,
autoIncrement:true
},
userId: {
type: seq.INTEGER,
},
friendUserId: {
type: seq.INTEGER,
},
favorite:{
type:seq.STRING,
null:true,
validate:{
isUrl: true,
}
},
},{
createdAt: Sequelize.DATE,
updatedAt: Sequelize.DATE,
}
);
User.hasMany(
User,
{
as: 'friends',
through: Friend,
foreignKey: 'friendUserId'
}
);
这篇关于将两个相同的外键作为序列中的两个不同字段添加到单个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!