gpt4 book ai didi

mysql - X 与 Y 无关(Sequelize/ExpressJS)

转载 作者:行者123 更新时间:2023-12-03 22:20:33 26 4
gpt4 key购买 nike

我是 NodeJS 的新手,有 express 和 Sequelize。当我想创建图书租赁时,控制台会提示我“图书与租赁无关”。
当我将表迁移到 sql 数据库时,id 就在它们的位置并且我的播种机正在工作。
你有解决办法吗?
错误:EagerLoadingError [SequelizeEagerLoadingError]:图书与租金无关!
书籍型号:

'use strict';
const { Model } = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class Book extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
this.belongsTo(models.Author);
this.belongsTo(models.Category);
this.hasMany(models.Rent, {
foreignKey: 'id'
});
}
}
Book.init(
{
authorId: DataTypes.INTEGER,
categoryId: DataTypes.INTEGER,
title: DataTypes.STRING,
description: DataTypes.TEXT,
amount: DataTypes.INTEGER
},
{
sequelize,
modelName: 'Book'
}
);
return Book;
};
租用型号:
'use strict';
const { Model } = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class Rent extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
this.belongsTo(models.User);
this.belongsTo(models.Book);
}
}
Rent.init(
{
userId: DataTypes.INTEGER,
bookId: DataTypes.INTEGER,
in: DataTypes.DATE,
back: DataTypes.DATE
},
{
sequelize,
modelName: 'Rent'
}
);
return Rent;
};
谢谢你们的帮助!

最佳答案

尝试用旧代码替换新代码。它指出,rent 有一个来自 book 表的外键,键为 bookId。
旧代码

 this.hasMany(models.Rent, {
foreignKey: 'id'
});
新代码
 this.hasMany(models.Rent, {
foreignKey: 'bookId'
});

关于mysql - X 与 Y 无关(Sequelize/ExpressJS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67794845/

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