在别名关联上顺序加载错误

问题描述

嗨,我有以下index.js @H_502_1@

var fs = require('fs');
var path = require('path');
var Sequelize = require('sequelize');
var CONfig = require('../config/config');

var sequelize = new Sequelize(CONfig.database,CONfig.user,CONfig.password,{
  host: CONfig.host,dialect: CONfig.dialect,port: CONfig.port,operatorsAliases: Sequelize.Op,logging: false
});

var db = {};


fs.readdirsync(__dirname)
  .filter(function (file) {
    return (file.indexOf('.') !== 0) && (file !== 'index.js');
  })
  .forEach(function (file) {
    var model = sequelize.import(path.join(__dirname,file));
    db[model.name] = model;
  });

Object.keys(db).forEach(function (modelName) {
  if ('associate' in db[modelName]) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

我想两次包含具有不同条件的模型,所以我打算在这种情况下使用别名:@H_502_1@

module.exports = function (sequelize,DataTypes) {
  var TSection = sequelize.define('TSection',{
    id: {
      type: DataTypes.INTEGER(11),allowNull: false,primaryKey: true,autoIncrement: true
    },name: {
      type: DataTypes.STRING(500),allowNull: true
    },TestId: {
      type: DataTypes.INTEGER(11),field: 'test_id',references: {
        model: 'test',key: 'id'
      }
    },},{
    tableName: 't_sections'
  });
  
  TSection.associate = function (models) {
    TSection.belongsTo(models.Test),{
      foreignKey: 'id',as: 'sections'
    },TSection.hasMany(models.TQuestion),{
      foreignKey: 'id'
    }
  };

  return TSection;
};

和@H_502_1@

module.exports = function (sequelize,DataTypes) {
  var Test = sequelize.define('Test',allowNull: true,{
    tableName: 'tests'
  })
  Test.associate = function (models) {
    Test.hasMany(models.TSection),{
      foreignKey: 'id'
    }
  }

  return Test;
};

当我尝试获取类似信息时:@H_502_1@

const test = await Test.findOne({
   attributes: ['id','name'],include: [{
     model: TSection,attributes: ['id',{
     model: TSection,as: 'sections'
     }]
 });

我有错误,我不知道是什么原因引起的: 注意:我已经尝试了几种组合,包括但不包括上述模型@H_502_1@

UnhandledPromiseRejectionWarning: Error: Error: SequelizeEagerLoadingError: TSection is associated to Test using an alias. You've included an alias (sections),but it does not match the alias(es) defined in your association (TSections).

我想你想知道我的目标是计算总部分的数量,但只检索一个(符合给定条件的部分) @H_502_1@

谢谢!@H_502_1@

解决方法

您在关联中添加了额外的括号。他们应该看起来像这样:

TSection.associate = function (models) {
    TSection.belongsTo(models.Test,{
      foreignKey: 'id',as: 'sections'
    });
    TSection.hasMany(models.TQuestion,{
      foreignKey: 'id'
    });
  };

Test.associate = function (models) {
    Test.hasMany(models.TSection,{
      foreignKey: 'id'
    })
  }