Ассоциация в Sequelize бросает ошибку как не подключен к - PullRequest
1 голос
/ 16 февраля 2020

Я новичок в базе данных и изучаю продолжение (Postgres). Я создаю веб-приложение для блогов и пытаюсь установить связь в моей БД, но получаю ошибку на стороне сервера, как error: creator is not associated with blogpost

, вот что я сделал до сих пор.

creator_model

const Sequelize = require('sequelize');
const db = require('../db/dbConfig');
const bcrypt = require('bcrypt');
const Creator = db.sequelize.define('creator', {
        id: {
          type: Sequelize.INTEGER,
          primaryKey: true,
          autoIncrement: true,
          allowNull: false
        },
        firstName: {
            type: Sequelize.STRING,
            allowNull: false
        },
        lastName: {
            type: Sequelize.STRING
        },
        email: {
            type: Sequelize.STRING,
            allowNull: false,
            unique: true
        },
        password: {
            type: Sequelize.STRING,
            allowNull: false
        }
    },
    {
        hooks: {
            beforeCreate: (Creator) => {
                Creator.password = bcrypt.hashSync(Creator.password,10)
            }
        }
    }
);
Creator.associate = (models) => {
    console.log('visited here')
        Creator.hasMany(models.BlogPost,{
            foreignKey: "creatorId",
            as: "owner",
            onDelete: 'CASCADE'
        });
    }
module.exports = Creator;

Blog_model

const Sequelize = require('sequelize');
const Creator = require('../models/CreatorModel');
const db = require('../db/dbConfig');
const BlogPost = db.sequelize.define('blogpost',{
    blogId: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true,
        allowNull: false
    },
    title: {
        type: Sequelize.STRING,
        allowNull: false
    },
    cover: {
        type: Sequelize.STRING,
        allowNull: false
    },
    body: {
        type: Sequelize.TEXT,
        allowNull: false
    },
    creatorId: {
        type: Sequelize.INTEGER,
        references:{
            model: Creator,
            key: 'id'
        },
        allowNull: false
    },
    likes: {
        type: Sequelize.INTEGER,
        defaultValue: 0
    }
},{});
BlogPost.associate = (models) => {
    BlogPost.hasMany(models.Comment,{
        foreignKey: 'postId',
        as: 'blogpost',
        onDelete: 'CASCADE'
    });
    BlogPost.belongsTo(models.Creator,{
        foreignKey: 'creatorId',
        as: 'creator',
        onDelete: 'CASCADE'
    })

}
module.exports = BlogPost;

Comment_model

const Sequelize = require('sequelize');

const BlogPost = require('../models/BlogPostModel');
const db = require('../db/dbConfig');
const Comment = db.sequelize.define('comment',{
    commentId: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true,
        allowNull: false
    },
    name: {
      type: Sequelize.STRING,
      allowNull: false  
    },
    email: {
        type: Sequelize.STRING,
        allowNull: false
    },
    message: {
        type: Sequelize.TEXT,
        allowNull: false
    },
    blogPostId: {
        type: Sequelize.INTEGER,
        references: {
            model: BlogPost,
            key: 'blogId'
        },
        allowNull: false
    }

},{});
Comment.associate = (models) => {
    Comment.belongsTo(models.BlogPost,{
        foreignKey: 'blogPostId',
        as: 'blog',
        onDelete: 'CASCADE'
    })
}
module.exports = Comment;

здесь мой конфиг БД с express и секвелированием

const Sequelize = require('sequelize');
const dotenv=require("dotenv");
dotenv.config();

const db ={}

const sequelize = new Sequelize(`${process.env.DB_NAME}`, `${process.env.DB_USERNAME}`, `${process.env.DB_PASSWORD}`, {
  host: 'localhost',
  dialect: 'postgres'
})

sequelize
  .authenticate()
  .then(() => {
    console.log('Connection has been established successfully.');
  })
  .catch(err => {
    console.error('Unable to connect to the database:', err);
  });

db.sequelize = sequelize
db.Sequelize = Sequelize


sequelize.sync()
  .then(() => {
    console.log(`Database & tables created!`)
  })
  .catch(error => console.log("DB error: ",error));

module.exports = db;

контроллера. js

const BlogPost = require('../models/BlogPostModel');
const Comment = require('../models/CommentModel');
const Creator = require('../models/CreatorModel');

const getAllBlog = (req,res) =>{
    BlogPost.findAll({
        include: [
            {
                model: Creator,
                as: "author",
                include: [{
                    model: Comment,
                    as: "comments"
                }]
            }
        ]
    })
    .then(data => {
        res.json(data)
    })
    .catch(error => {
        res.status(500).json({error: error.message})
    })
}
module.exports = {
    getAllBlog
}
...