gpt4 book ai didi

node.js - 从 Controller 使用 "sequelize"中的模型

转载 作者:行者123 更新时间:2023-12-03 22:34:35 32 4
gpt4 key购买 nike

我正在使用由 sequelice-cli 创建的模型,但是当我使用它时,我收到一条错误消息。
我正在使用 ORM( Sequelize ),当我尝试访问模型的方法时,例如 finOne()findAll()update() ,它无法识别它并抛出错误,我已经尝试以另一种方式工作,但它不正确,我正在使用 sequelize-cli 生成模型
我需要你的帮助,请!!!
这是我的模型:

'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class scholarship_student 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
}
};
scholarship_student.init({
id: DataTypes.INTEGER,
name: DataTypes.STRING,
last_name: DataTypes.STRING,
status: DataTypes.ENUM("Activo", "Inactivo")
}, {
sequelize,
modelName: 'scholarship_student',
});


return scholarship_student;
};
这是我的 Controller
const becadosController = {};
const db = require("../models/index");
const validation = require("../validation");
const scholarship_student = require("../models/scholarship_student");

becadosController.get = async (req, res) => {

await scholarship_student.findAll()
.then((student) => {
res.json(student);
})
.catch((err) => {
console.log(err);
res.sendStatus(500);
});
};
错误:
enter image description here

最佳答案

您必须设置一个连接配置,然后您将作为参数传递给您的模型实例。
例子:

const connection = new Sequelize(
yourDatabaseName,
yourDatabaseUsername,
yourDatabasePassword,
{
host: yourDatabaseHost,
dialect: 'whateverDialectYouAreUsing', // example 'mssql'
}
)
然后
await scholarship_student(connection).findAll()
.then((student) => {
res.json(student);
})
.catch((err) => {
console.log(err);
res.sendStatus(500);
});

关于node.js - 从 Controller 使用 "sequelize"中的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62685728/

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