Sequelize Associations Error Users.hasMany called with something that's not a subclass of Sequelize.Model. when associating between 2 models

huangapple go评论58阅读模式
英文:

Sequelize Associations Error Users.hasMany called with something that's not a subclass of Sequelize.Model. when associating between 2 models

问题

我在关联两个模型(Users 和 Comments)时遇到了一个错误:“Users.hasMany 调用的参数不是 Sequelize.Model 的子类。” 但是当我移除 const Users = require("./user");Comments.belongsTo(Users, { foreignKey: "userId", onDelete: "cascade" }); 这两行代码时,我会得到一个错误:“Users 未与 Comments 关联!” 我已经在用户模型中进行了关联。

这是我的Comments模型:

const { DataTypes } = require("sequelize");
const { sequelize } = require(".");
const Users = require("./user");

const Comments = sequelize.define("Comments", {
    comment: {
        type: DataTypes.STRING,
        allowNull: false,
        validate: {
            min: 1,
            max: 50,
        },
    },
});
// 如果我从代码中移除这部分,我会得到“Users 未与 Comments 关联!”的错误。

Comments.belongsTo(Users, {
    foreignKey: "userId",
    onDelete: "cascade",
});

//

module.exports = Comments;

这是我的Users模型:

const { DataTypes } = require("sequelize");
const { sequelize } = require(".");
const Comments = require("./comment");
const jwt = require("jsonwebtoken");

const Users = sequelize.define("Users", {
    username: {
        type: DataTypes.STRING,
        allowNull: false,
        unique: true,
        validate: {
            min: 5,
            max: 30,
            notNull: true,
        },
    },
});

Users.hasMany(Comments, {
    foreignKey: "userId",
    onDelete: "cascade",
});

module.exports = Users;

我还有一个用于检索所有评论的 GET 请求,我想在其中包括 Users 表,以便我可以访问创建该评论的用户的用户名:

const getComments = async (req, res) => {
    const comments = await Comments.findAll({
        include: Users,
    });
    res.send(comments);
};
英文:

I am encountering an error Users.hasMany called with something that's not a subclass of Sequelize.Model. when associating between 2 models (Users and Comments). BUT when i remove const Users = require("./user"); and Comments.belongsTo(Users, { foreignKey: "userId", onDelete: "cascade", });
from the Comments model i instead get "Users is not associated to Comments!" error. I already associated it in the users model.

This is my model for Comments:

const { DataTypes } = require("sequelize");
const { sequelize } = require(".");
const Users = require("./user");

const Comments = sequelize.define("Comments", {
    comment: {
        type: DataTypes.STRING,
        allowNull: false,
        validate: {
            min: 1,
            max: 50,
        },
    },
});
// If i remove this from the code i instead get Users is not associated to Comments!

Comments.belongsTo(Users, {
    foreignKey: "userId",
    onDelete: "cascade",
});

//

module.exports = Comments;

This is my Users model:

const { DataTypes } = require("sequelize");
const { sequelize } = require(".");
const Comments = require("./comment");
const jwt = require("jsonwebtoken");

const Users = sequelize.define("Users", {
    username: {
        type: DataTypes.STRING,
        allowNull: false,
        unique: true,
        validate: {
            min: 5,
            max: 30,
            notNull: true,
        },
    },
});

Users.hasMany(Comments, {
    foreignKey: "userId",
    onDelete: "cascade",
});

module.exports = Users;

I also have a GET request for retrieving all comments where I would like to include the Users table so that I have access to the username of the user that created that comment:

const getComments = async (req, res) => {
    const comments = await Comments.findAll({
        include: Users,
    });
    res.send(comments);
};

答案1

得分: 1

你可以定义一个单独的全局方法来处理关联:

const Users = require("./user");
const Comments = require("./comment");

const sequelize = new Sequelize(...);

export const sync = async () => {
    Comments.belongsTo(Users, {
        foreignKey: "userId",
        onDelete: "cascade",
    });

    Users.hasMany(Comments, {
        foreignKey: "userId",
        onDelete: "cascade",
    });

    await sequelize.sync();
}

然后,在初始化数据库/应用程序时使用它:

import { sync } from './path/to/sync';

await sync();

这将确保在关联时两个模型都已定义。

英文:

You could define a separate global method for handling associations:

const Users = require("./user");
const Comments = require("./comment");

const sequelize = new Sequelize(...);

export const sync = async () => {
    Comments.belongsTo(Users, {
        foreignKey: "userId",
        onDelete: "cascade",
    });

    Users.hasMany(Comments, {
        foreignKey: "userId",
        onDelete: "cascade",
    });

    await sequelize.sync();
}

Then, use it when initializing the database/application:

import { sync } from './path/to/sync';

await sync();

This will ensure both models are defined when associated.

huangapple
  • 本文由 发表于 2023年6月16日 01:25:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76484138.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定