【发布时间】:2017-01-24 00:02:53
【问题描述】:
我正在尝试在商店表和产品之间创建 1:1 关系。 每个产品都应该有一个shop table的外键,每个shop都应该有product的外键。
我已经定义了这两个表。
module.exports = function( sequelize , DataTypes ){
var shops = sequelize.define('shops',{
id: {
type: DataTypes.INTEGER,
allowNull:false,
primaryKey:true,
autoIncrement:true
},
name:{
type:DataTypes.STRING,
allowNull:false
},
address:{
type: DataTypes.STRING,
allowNull:false
},
web:{
type: DataTypes.STRING,
allowNull:false
},
price:{
type: DataTypes.INTEGER,
allowNull:false
}
})
return shops
}
`
var shop = require('./shops.js');
module.exports = function( sequelize , DataTypes ){
var component = sequelize.define('component',{
id: {
type: DataTypes.INTEGER,
allowNull:false,
primaryKey:true,
autoIncrement:true
},
name:{
type: DataTypes.STRING,
allowNull:false
},
storage:{
type: DataTypes.INTEGER,
allowNull:false
},
bilance:{
type: DataTypes.INTEGER,
allowNull:false
}
},{
classMethods:{
associate:function(models){
component.hasOne(shop,{foreignKey:'foreign_key'})
}
}
})
return component;
}
在 db.js 文件中使用它连接它。
db.shop.belongsTo(db.component)
db.component.hasOne( db.shop ,{foreignKey : 'shop_id'})
但是这增加了 componentId {foreign key} 和 shop_id 另一个外键,它们都到了 shop 表中。
如果我替换 1:1 关系 if 1:n e.g
db.component.hasMany(..)
它做同样的事情,将两个外键添加到商店表中
【问题讨论】:
标签: node.js sqlite sequelize.js