gpt4 book ai didi

sequelize.js - 为什么不使用模型关联创建外键

转载 作者:行者123 更新时间:2023-12-03 22:20:09 25 4
gpt4 key购买 nike

我在下面创建了一个关系,一个公司有很多分支机构:

索引.js:

'use strict';

var fs = require('fs');
var path = require('path');
var Sequelize = require('sequelize');
var basename = path.basename(module.filename);
var env = process.env.NODE_ENV || 'development';
var config = require(__dirname + '/..\\config\\config.json')[env];
var db = {};

if (config.use_env_variable) {
var sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
var sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(function(file) {
var model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});

Object.keys(db).forEach(function(modelName) {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

公司.js
'use strict';
module.exports = function(sequelize, DataTypes) {
var companies = sequelize.define('companies', {
companyId: {
type: DataTypes.UUID,
primaryKey: true
},
companyName: DataTypes.STRING(50)
}, {
classMethods: {
associate: function(models) {
companies.hasMany(models.branches, {
foreignKey: 'branchId'
});
}
}
});
return companies;
};

分支.js:
'use strict';
module.exports = function(sequelize, DataTypes) {
var branches = sequelize.define('branches', {
branchId: {
type: DataTypes.UUID,
primaryKey: true
}
}, {
classMethods: {
associate: function(models) {
branches.belongTo(models.companies, {
onDelete: "CASCADE",
foreignKey: 'companyId'
});
}
}
});
return terminals;
};

当我 model.sync() 时,不会创建外键关系。

最佳答案

如果您使用 4.0 或更高版本,它们更改了在模型中定义关联的方式。 This 是一篇很棒的文章,重点介绍了一些更改,包括本期提到的更改。

例如你的 branch.js 文件应该是这样的:

'use strict';
module.exports = function(sequelize, DataTypes) {
var branches = sequelize.define('branches', {
branchId: {
type: DataTypes.UUID,
primaryKey: true
}
});

branches.associate = (models) => {
branches.belongTo(models.companies, {
onDelete: "CASCADE",
foreignKey: 'companyId'
});
}
return branches;
};

关于sequelize.js - 为什么不使用模型关联创建外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45204430/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com