我有一个名为的模型Task,它可以有许多父任务(多个祖先)和/或子任务.
如果我在没有Sequelize的情况下对此进行建模,我会有一个名为的表ParentTasks,它将具有a ParentTaskId和a TaskId来确定关系,以及一个Tasks表id作为主键.
使用Sequelize,这可能吗?我尝试了很多不同的排列和组合,但没有一个导致我想要的东西.
任何帮助,将不胜感激.
谢谢.
你有什么尝试?
这个怎么样:
var Task = sequelize.define('Task', {
name: Sequelize.STRING
});
Task.hasMany(Task, { as: 'children', foreignKey: 'ParentTaskId', through: 'ParentTasks' });
Task.hasMany(Task, { as: 'parents', foreignKey: 'TaskId', through: 'ParentTasks' });
Run Code Online (Sandbox Code Playgroud)
根据上述评论中的 Asaf,hasMany 不再有效。这是使用belongsToMany的解决方案:
用户模型:
module.exports = (sequelize, DataTypes) => {
const Users = sequelize.define('Users', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
allowNull: false,
autoIncrement: true
},
name: {
type: DataTypes.STRING,
allowNull: false
}
}, {
freezeTableName: true
});
Users.associate = function(models) {
Users.belongsToMany(models.Users, { through: models.UserUsers, as: 'Parents', foreignKey: 'parentId' });
Users.belongsToMany(models.Users, { through: models.UserUsers, as: 'Siblings', foreignKey: 'siblingId' });
};
return Users;
};
Run Code Online (Sandbox Code Playgroud)
用户用户模型:
module.exports = (sequelize, DataTypes) => {
const UserUsers = sequelize.define('UserUsers', {
}, {
freezeTableName: true
});
UserUsers.associate = function(models) {
UserUsers.belongsTo(models.Users, { as: 'Parent', onDelete: 'CASCADE'});
UserUsers.belongsTo(models.Users, { as: 'Sibling', onDelete: 'CASCADE' });
};
return UserUsers;
};
Run Code Online (Sandbox Code Playgroud)
使用它你设置并得到这样的:
models.Users.findOne({ where: { name: 'name' } })
.then(u1 => {
models.Users.findOne({ where: { name: 'name2'} })
.then(u2 => {
u2.addSibling(u1);
// or if you have a list of siblings you can use the function:
u2.addSiblings([u1, ...more siblings]);
});
});
Run Code Online (Sandbox Code Playgroud)
和
models.Users.findOne({ where: { name: 'name'} })
.then(person => {
person.getSiblings()
.then(siblings => { console.log(siblings) });
});
Run Code Online (Sandbox Code Playgroud)
参考资料:Sequelize 文档