mysql-如何包括带有sequelize-fixtures的json文件中的关联?
作者:互联网
大家好
我对sequelizejs很陌生,只是尝试使用它.我在使用sequelize-fixtures创建示例数据集时遇到问题.
我的模型是这样创建的:
User.js(不包含beforeCreate,beforeUpdate挂钩)
'use strict';
module.exports = function (sequelize, DataTypes) {
var User = sequelize.define('User', {
email: {type: DataTypes.STRING, allowNull: false},
password: {type: DataTypes.STRING, allowNull: false},
active: {type: DataTypes.BOOLEAN, default: false}
});
return User;
};
Role.js
'use strict';
module.exports = function (sequelize, DataTypes) {
var Role = sequelize.define('Role', {
title: {type: DataTypes.STRING, allowNull: false},
description: {type: DataTypes.STRING, allowNull: true},
code: {type: DataTypes.STRING, allowNull: false}
});
return Role;
};
将模型导入模型对象后,我创建了它们之间的关联:
models.User.belongsToMany(models.Role, {through: 'UserRole', constraints: true});
models.Role.belongsToMany(models.User, {through: 'UserRole', constraints: true});
正如文档所说,我已经从与该结构一起使用的json文件中加载了示例数据,但是由sequelize自动创建的userroles表仍然为空.
json文件包含以下内容:
[
{
"model": "Role",
"data": {
"title": "Administrator",
"description": "Administrator users",
"code": "RIGHT_ADMIN"
}
},
{
"model": "Role",
"data": {
"title": "Manager",
"description": "Manager users",
"code": "RIGHT_MANAGEMENT"
}
},
{
"model": "User",
"keys": [
"id"
],
"data": {
"id": 0,
"email": "admin@app.io",
"password": "admin",
"active": true
},
"roles":[1,2]
}
]
db同步后,将调用夹具加载:
force:正确,仅出于发展原因保留在其中
db.sync({force: true}).then(function () {
//load fixtures
SequelizeFixtures.loadFile('fixtures/*.json', models).then(function () {
console.dir("DEV DATA CREATED SUCCESSFULLY");
});
});
我的问题是,运行夹具后,由用户和角色模型的关联创建的userroles表始终保持为空.
解决方法:
想通了
事实证明,sequelize夹具文档说可以在json文件中给定模型记录的数据之外定义many2many关系值.
解决方案是在Model的$Model.associations对象中找到关系关联键,并将其用作数据对象内的键.
简而言之:
这个
models.User.belongsToMany(models.Role, {through: 'UserRole', constraints: true});
models.Role.belongsToMany(models.User, {through: 'UserRole', constraints: true});
创建用户模型的关联“角色”和角色模型的关联“用户”.
现在,根据此json记录对象应如下所示:
{
"model": "User",
"keys": [
"id"
],
"data": {
"id": 0,
"email": "admin@app.io",
"password": "admin",
"active": true,
"Roles":[1,2]
}
}
Here is a gist I’have made to show how to use it.
希望这将有助于其他使用sequelize和sequelize-fixtures的用户
标签:fixtures,sequelize-js,node-js,json,mysql 来源: https://codeday.me/bug/20191027/1946741.html