Sequelize: TypeError: hasOne不是函数



嗨,我是新来的序列化hasOne关联不适合我,我正试图使两个表一个表

  1. 包含经销商名称和描述的经销商
  2. DealerProducts包含经销商的产品和价格以及表1作为FKEY(我希望hasOne为我创建FKEY)

所以我要创建3个文件每个文件一个然后是index。js文件来收集它们并将它们关联起来

这些文件:

dealer-model.js

module.exports = (sequelize = require('../db')) => {
const { DataTypes } = require('sequelize');
const Dealer = sequelize.define('Dealer', {
did: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
allowNull: false,
primaryKey: true
},
name: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
len: [1, 50]
}
},
description: {
type: DataTypes.STRING,
allowNull: true,
},
}, {
tableName: 'dealers',
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
// paranoid: true
})
return Dealer;
}

dealer-products-model.js

module.exports = (sequelize = require('../db')) => {
const { DataTypes } = require('sequelize');
const DealerProduct = sequelize.define('DealerProduct', {
dpid: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
allowNull: false,
primaryKey: true
},
product_name: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
len: [1, 100]
}
},
type: {
type: DataTypes.STRING,
allowNull: true,
validate: {
len: [1, 100]
}
},
description: {
type: DataTypes.TEXT,
allowNull: true
},
price: {
type: DataTypes.DECIMAL(10, 2),
allowNull: false
},
quantity: {
type: DataTypes.INTEGER,
allowNull: false
}
}, {
tableName: 'dealer_products',
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
// paranoid: true
})
return DealerProduct;
}

然后index.js

module.exports = async (sequelize = require('../db')) => {
const { DataTypes } = require('sequelize');
const User = require('./user-model');
const Dealer = require('./dealers-model');
const DealerProduct = require('./dealer-products-model');
User(sequelize)
Dealer(sequelize)
DealerProduct(sequelize)
DealerProduct.hasOne(Dealer, {
foreignKey: {
type: DataTypes.UUID,
allowNull: false,
name: "dealers_did"
}
});
Dealer.belongsTo(DealerProduct);
sequelize.sync({alter: true}); //force: true
}

这是为我的postgres创建表,但是关联不起作用,因为我没有为DealerProducts创建FKEY列

这是我得到的错误

TypeError: DealerProduct。hasOne不是一个函数

我哪里错了?

UPDATE

我的答案很简单,就是将Dealer和DealerProduct保存为变量,然后使用变量作为has_value。


const dealer = Dealer(sequelize)
const dealerProduct = DealerProduct(sequelize)
dealer.hasOne(dealerProduct, {
foreignKey: {
type: DataTypes.UUID,
allowNull: false,
name: "dealers_did"
}
});
dealerProduct.belongsTo(dealer);```
So this worked

相关内容

  • 没有找到相关文章

最新更新