【问题标题】:Sequelize hasMany is working fine but the inverse relation is not workingSequelize hasMany 工作正常,但反比关系不起作用
【发布时间】:2020-04-19 09:11:21
【问题描述】:

我正在尝试使用 Sequelize 在 Node Js(express Js) 中处理 mysql 关系。

User.hasMany(Post); 工作得很好,但是当我尝试在 Post 模型中反转它时:Post.belongsTo(User);

收到此错误: throw new Error(${source.name}.${_.lowerFirst(Type.name)} 调用的东西不是 Sequelize.Model 的子类);

错误:post.belongsTo 调用的东西不是 Sequelize.Model 的子类

用户模型如:

const Sequelize = require('sequelize');
const db = require('../config/db');

const Post = require('./Post');

const User = db.define('user', {
    id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        notNull: true,
        primaryKey: true
    },
    name: {
        type: Sequelize.STRING,
        notNull: true
    },
    email: {
        type: Sequelize.STRING,
        notNull: true
    },
    password: {
        type: Sequelize.STRING,
        notNull: true
    }

});

User.hasMany(Post);

module.exports = User;

和 Post 模型一样:

const Sequelize = require('sequelize');
const db = require('../config/db');

const User = require('./User');

const Post = db.define('post', {
    id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        notNull: true,
        primaryKey: true
    },

    title: {
        type: Sequelize.STRING,
        notNull: true
    },
    description: {
        type: Sequelize.TEXT,
        notNull: true
    },
    author: {
        type: Sequelize.STRING,
        notNull: true
    }
});

Post.belongsTo(User);

module.exports = Post;

我该如何解决这个问题? 谢谢大家...

【问题讨论】:

    标签: mysql node.js express sequelize.js


    【解决方案1】:

    您应该更正您的模型定义导出为函数,并像这样在每个模型定义函数中定义 associate 函数,并在所有模型都注册到诸如 database.js 之类的模块中之后调用它:

    user.js

    module.exports = (sequelize, DataTypes) => {
      const User = sequelize.define('user', {
        id: {
            type: Sequelize.INTEGER,
            autoIncrement: true,
            notNull: true,
            primaryKey: true
        },
       ...
    
      User.associate = function (models) {
        User.hasMany(models.Post)
      }
    
    

    post.js

    module.exports = (sequelize, DataTypes) => {
      const Post = sequelize.define('post', {
        id: {
            type: Sequelize.INTEGER,
            autoIncrement: true,
            notNull: true,
            primaryKey: true
        },
      ...
      Post.associate = function (models) {
        Post.belongsTo(models.User)
      }
    
    

    【讨论】:

    • 您不应该在其他模型文件中导入模型定义来关联它们。首先您需要注册您的模型,其次您需要调用已注册模型定义函数的所有关联函数。不要循环引用你的模型定义。
    • 如果我将这两个模型写在一个文件中,那么 hasMany 和 belongsTo 都可以正常工作。但我想在单独的文件中。
    • 将它们定义为具有关联函数的函数,如上所示。然后在 database.js 之类的东西中调用所有模型定义函数,然后调用所有关联函数
    • 我如何准确地调用所有关联函数?你能帮我描述一下吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-08
    • 1970-01-01
    • 2020-03-27
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    • 1970-01-01
    相关资源
    最近更新 更多