如何在两个模型之间建立一对多关联?

时间:2020-05-26 12:44:34

标签: node.js postgresql express sequelize.js

我制作了两个续集模型,一个用于存储学生,另一个用于存储任务。 我想在学生和任务模型之间建立一对多的关系...

任务模型

const Student= require('./student.js')
module.exports = (sequelize, Sequelize) => {
  const Task = sequelize.define("task", {
    title: {
      type: Sequelize.STRING
    },
    description: {
      type: Sequelize.STRING
    }
  });

  Task.associate = (Student) => {
     Task.belongsTo(Student) 
  };
  return Task;
};

学生模型

const Task = require('./task.js')

module.exports = (sequelize, Sequelize) => {

    const Student = sequelize.define("student", {
      name: {
        type: Sequelize.STRING,
        allowNull:false
      },
      email: {
        type: Sequelize.STRING,
        unique:true,
        allowNull:false
      },
      branch: {
        type: Sequelize.STRING,
        allowNull:false
      },
      id: {
            type: Sequelize.INTEGER,
            autoIncrement: true,
            primaryKey: true
        },
    });

    Student.associate = (Task) =>{
        Student.hasMany(Tasks, {as: "tasks"))
    }
    return Student;
  };

我想获取每个学生的任务以及学生数据。 下面是相同的功能

///从数据库中检索所有学生。

const Task= require('../models/task.js')

exports.findAll = (req, res) => {

    Student.findAll({
      include: Task
    })
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while retrieving students."
      });
    });
};


但是当我查询时,出现以下错误。

{
    "message": "task is not associated to student!"
}

我在此问题上停留了2天...请帮助我解决该问题。 预先谢谢你

0 个答案:

没有答案
相关问题