【问题标题】:Express js: Sequlize belongsto returns empty resultsExpress js:Sequelize belongsto 返回空结果
【发布时间】:2019-10-27 07:40:06
【问题描述】:

我有两个模型

座位分配

module.exports = (sequelize, DataTypes) => {
  const SeatAllocation = sequelize.define('SeatAllocation', {
    id:{
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV1,
        primaryKey: true
    },   
    course_id: {
      type:DataTypes.UUID,
      allowNull:false,
      references: {
        model: 'Courses', 
        key: 'id', 
     }
    },
    number_of_seats:{
      type:DataTypes.INTEGER,
      allowNull:false
    },
    allocation_date:{
        type:DataTypes.STRING,
        allowNull:false
    }
  },{
    timestamps: false
  }
  );

  SeatAllocation.associate = function (models) {
    models.SeatAllocation.belongsTo(models.Course, {
      onDelete: "CASCADE",  
      foreignKey:'course_id',
      targetKey:'id',
      as:'Courses'
    });
  };

  return SeatAllocation;
};

课程

module.exports = (sequelize, DataTypes) => {
  const Course = sequelize.define('Course', {
    id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV1,
        primaryKey: true
    },   
    name: {
      type:DataTypes.STRING,
      allowNull:false
    },
    created_at:{
      type:DataTypes.STRING,
      allowNull:false
    },
    updated_at:{
      type:DataTypes.STRING,
      allowNull:false
    }

  },{
    timestamps: false
  }
  );

  Course.associate = function(models) {
    models.Course.hasMany(models.SeatAllocation,{
      foreignKey:'course_id',
      as:'Courses'
    });
  };


  return Course;
};

我正在尝试从座位分配表中获取所有值以及课程详细信息 这是我迄今为止尝试过的查询

await models.SeatAllocation.findAll({
            include:[{
                model:models.Course,
                as:'Courses',
                all:true,
                required:true
            }]
        });

我得到了结果,但是结果中缺少 courses 对象

【问题讨论】:

    标签: mysql express sequelize.js belongs-to


    【解决方案1】:

    SeatAllocation 中的一个可能疏忽 - models.Task 是怎么回事?您不想将SeatAllocationCourse 关联吗?生成的 SQL 是什么样的?

      SeatAllocation.associate = function (models) {
        models.Task.belongsTo(models.Course, {   
          onDelete: "CASCADE",
    

    【讨论】:

    • 抱歉模型Task实际上是一个错字我已经更新了我的问题
    • 我测试了一些非常相似的东西,它工作正常。可以在 MySql Workbench 中执行生成的查询吗?
    【解决方案2】:

    以删除模型的方式进行两个关联。课程使用 Course 代替为我工作

    Course.associate = function(models) {
        Course.hasMany(models.SeatAllocation,{
          foreignKey:'course_id',
          as:'Courses'
        });
      };
    

    【讨论】:

    • 我没有得到你的答案,请添加更多解释
    • 将此部分 models.SeatAllocation.belongsTo 替换为 SeatAllocation.belongsTo 导致您在上面获取模型变量,但您想从模型对象中提取它
    猜你喜欢
    • 1970-01-01
    • 2020-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-15
    相关资源
    最近更新 更多