gpt4 book ai didi

node.js - 为什么在Sequelize 中关联belongsTo 会给我这个错误?

转载 作者:行者123 更新时间:2023-12-03 22:31:13 25 4
gpt4 key购买 nike

我被这个问题困扰了很长一段时间,我不知道我的代码有什么问题,我试图将一个表与另一个表相关联,但只有一半有效,任何帮助将不胜感激。
模型/公司.js

const DataTypes = require('sequelize');
const sequelize = require('../config/database');
const Users = require('./users');

const Companies = sequelize.define(
'companies',
{
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER
},
name: {
type: DataTypes.STRING(50),
unique: true,
allowNull: false
},
image_url: {
type: DataTypes.STRING(100),
unique: true
},
created_at: {
allowNull: true,
type: DataTypes.DATE,
defaultValue: Date.now()
},
updated_at: {
allowNull: true,
type: DataTypes.DATE,
defaultValue: Date.now()
}
},
{
//Rewrite default behavior of sequelize
timestamps: false,
paranoid: true,
underscored: true
}
);

Companies.hasMany(Users);
Users.belongsTo(Companies);


Companies.sync();

module.exports = Companies;
模型/用户.js
const DataTypes = require('sequelize');
const sequelize = require('../config/database');

const Users = sequelize.define(
'users',
{
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER
},
name: {
type: DataTypes.STRING(40),
allowNull: false
},
email: {
type: DataTypes.STRING(60),
allowNull: false,
unique: true
},
password: {
type: DataTypes.STRING(60)
},
role: {
type: DataTypes.STRING(40),
allowNull: false
},
image_url: {
type: DataTypes.STRING(100),
unique: true
},
batch: {
type: DataTypes.STRING(3)
},
major: {
type: DataTypes.STRING(10)
},
company_id: {
type: DataTypes.INTEGER,
allowNull: false
},
created_at: {
allowNull: true,
type: DataTypes.DATE,
defaultValue: Date.now()
},
updated_at: {
allowNull: true,
type: DataTypes.DATE,
defaultValue: Date.now()
}
},
{
//Rewrite default behavior of sequelize
timestamps: false,
paranoid: true,
underscored: true
}
);

Users.sync();

module.exports = Users;
然后在我尝试在下面运行此代码之后
const Companies = require('./database/models/companies');
const Users = require('./database/models/Users');

//Relation 1: Company and Users
Companies.findAll({ include: [ Users ] }).then((res) => console.log(res));
Users.findAll({ include: [ Companies ] }).then((res) => console.log(res));
它给了我这个错误:
(node:4893) UnhandledPromiseRejectionWarning: SequelizeEagerLoadingError: companies is not associated to users!
我在网上尝试了几种解决方案,但在这种情况下没有帮助。

最佳答案

BelongsTo 意味着一对一的关系,而一个公司可能有多个用户(意思是,在 BelongsTo 冲突后调用 hasMany!)。
更多信息:https://sequelize.org/master/manual/assocs.html

关于node.js - 为什么在Sequelize 中关联belongsTo 会给我这个错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66730536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com