有人可以用Sequelize.js中的自定义联结表向我展示N:M关联的2019年示例(对同一模型)吗?
我正在尝试建立User
模型的朋友系统。我的系统(上述)在Windows上运行良好,但在Linux上却无法运行(似乎再次遇到字母问题),因此我想举一个完整的示例,说明在哪里都能奏效。
我当前的代码:
型号User
:
const model = sequelize.define("User", {
username: {
type: DataTypes.STRING(32),
unique: true,
allowNull: false
},
...
}, {});
model.associate = models => {
model.belongsToMany(model, {
through: "Friends", //I also tried models.Friend but it not work on both
as: "friend",
foreignKey: "user_id" //I also tried models.Friend.user_id but it not work on both
});
model.belongsToMany(model, {
through: "Friends", //I also tried models.Friend but it not work on both
as: "friendof",
foreignKey: "friend_id" //I also tried models.Friend.friend_id_id but it not work on both
});
};
return model;
模型Friend
:
module.exports = (sequelize, DataTypes) => {
const model = sequelize.define("Friend", {
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
}
}, {
hooks: {}
});
model.associate = models => {
// User have many Users as Friends
model.belongsTo(models.User, {
foreignKey: "user_id"
});
model.belongsTo(models.User, {
foreignKey: "friend_id"
});
};
return model;
};
在Windows环境(XAMPP,MariaDB)上运行良好,但在Linux(相同版本的DB和Sequelize)上则无法运行。由于尝试创建两个表(friends
,Friends
)而失败。当我使用through: models.Friend
时,它可以工作,但是Friend
表中没有id
。