sqlize/hasOne 中的关系不起作用 [英] Relations in sqlize / hasOne does not work
问题描述
我正在尝试在商店表和产品之间建立 1:1 的关系.每个产品都应该有一个店铺表的外键,每个店铺都应该有一个产品的外键.
I am trying to create 1:1 relation between table of shops and product. Each product should have an foreign key of shop table and each shop should have foreign key of product.
我已经定义了这两个表.
i have defined those two tables.
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');
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 文件中使用一个连接它.
inside db.js file a connected it using.
db.shop.belongsTo(db.component)
db.component.hasOne( db.shop ,{foreignKey : 'shop_id'})
但是这添加了 componentId {foreign key} 和 shop_id 另一个外键,它们都添加到 shop 表中.
but this added componentId {foreign key} and shop_id another foreign key ,both of them to the shop table.
如果我替换 1:1 关系 if 1:n e.g
If i replace 1:1 relation if 1:n e.g
db.component.hasMany(..)
它做同样的事情,将两个外键添加到商店表中
It does the same thing , adds both foreign keys into the shops table
推荐答案
您需要从回调方法中提供给您的 models 对象中引用 shop.所以在这种情况下你会这样做:
You need to reference shop from the models object provided to you in the callback method. So in this case you'd do:
classMethods:{
associate:function(models){
component.hasOne(models.shop,{foreignKey:'component_shop_FK'})
}
}
注意如果你想给FK添加一个约束(比如not null),简单的添加allowNull: false
.
Note if you want to add a constraint (such as not null) to the FK, simple add allowNull: false
.
我相信您引用了错误的模型.您已经为商店对象列出了商店",因此请尝试将 models.shop
更改为 models.shops
!
I believe you're referencing the wrong model. You've listed 'shops' for your shop object, so try changing models.shop
to models.shops
!
这篇关于sqlize/hasOne 中的关系不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!