为什么外键不是使用模型关联创建的

时间:2017-07-20 03:10:34

标签: sequelize.js

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

index.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;

companies.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;
};

branches.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()时,不会创建外键关系。

1 个答案:

答案 0 :(得分:1)

如果您使用的是4.0或更高版本,则会更改如何在模型中定义关联。 This是一篇很棒的文章,强调了一些变化,包括本期提到的变化。

例如,您的branches.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;
};