2017-07-20 33 views
0

我craeted下面的關係產生,一個公司有許多分支:爲什麼外國密鑰不與模型關聯

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

分支.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(),沒有創建外鍵關係。

回答

0

如果您使用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; 
}; 
+0

耶我想出來剛纔您發佈之前,我會檢查它是否正常工作。 – Alvin

+0

我更新了我的答案,但您也在原始帖子中返回終端而不是分支。 – joshrathke