关系表上的NodeJS PostgreSQL Express SequelizeEagerLoadingError

Posted

技术标签:

【中文标题】关系表上的NodeJS PostgreSQL Express SequelizeEagerLoadingError【英文标题】:NodeJS PostgreSQL Express SequelizeEagerLoadingError on relationship table 【发布时间】:2022-01-05 06:54:59 【问题描述】:

我遇到了无法从 NodeJS PostgreSQL 和 Express 访问关系数据表的问题。

首先是我的简单表格:

如你所见,我的“jenis”表与“kategori”表有关联,一个jenis可以有多个categori,一个categori只能包含一个jenis。

这是我在 Postgres Sequelize 上的迁移:

jenis-migration.js

"use strict";
module.exports = 
  up: async (queryInterface, Sequelize) => 
    await queryInterface.createTable("Umkm_Jenis", 
      id: 
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER,
      ,
      nama: 
        type: Sequelize.STRING,
      ,
      createdAt: 
        allowNull: false,
        type: Sequelize.DATE,
      ,
      updatedAt: 
        allowNull: false,
        type: Sequelize.DATE,
      ,
    );
  ,
  down: async (queryInterface, Sequelize) => 
    await queryInterface.dropTable("Umkm_Jenis");
  ,
;

categori-migration.js

"use strict";
module.exports = 
  up: async (queryInterface, Sequelize) => 
    await queryInterface.createTable("Umkm_Kategori", 
      id: 
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER,
      ,
      jenis_id: 
        type: Sequelize.INTEGER,
        allowNull: false,
      ,
      nama: 
        type: Sequelize.STRING,
        allowNull: false,
      ,
      createdAt: 
        allowNull: false,
        type: Sequelize.DATE,
      ,
      updatedAt: 
        allowNull: false,
        type: Sequelize.DATE,
      ,
    );
  ,
  down: async (queryInterface, Sequelize) => 
    await queryInterface.dropTable("Umkm_Kategori");
  ,
;

jenis.model.js

"use strict";
const  Model  = require("sequelize");
module.exports = (sequelize, DataTypes) => 
  class Umkm_Jenis extends Model 
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) 
      // define association here
      this.hasMany(models.Umkm_Kategori, 
        foreignKey: "jenis_id",
        as: "umkm_kategori",
      );
    
  
  Umkm_Jenis.init(
    
      nama: DataTypes.STRING,
    ,
    
      sequelize,
      modelName: "Umkm_Jenis",
      freezeTableName: true,
    
  );
  return Umkm_Jenis;
;

categori-model.js

"use strict";
const  Model  = require("sequelize");
module.exports = (sequelize, DataTypes) => 
  class Umkm_Kategori extends Model 
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) 
      // define association here
      this.belongsTo(models.Umkm_Jenis, 
        foreignKey: "jenis_id",
        as: "umkm_jenis",
      );
    
  
  Umkm_Kategori.init(
    
      jenis_id: DataTypes.INTEGER,
      nama: DataTypes.STRING,
    ,
    
      sequelize,
      modelName: "Umkm_Kategori",
      freezeTableName: true,
    
  );
  return Umkm_Kategori;
;

我在 postgres 上为 jenis 和 categori 表创建了一些播种机数据。

现在我希望我的 getAllKategori API 使用我建立的关系实际包含“jenis”表中的值。下面是我的 apiController 类别:

exports.findAllKategori = async (req, res) => 
  //check if theres a filter applied
  const nama = req.query.nama;
  const condition = nama ?  nama:  [Op.iLike]: `%$nama%`   : null;

  try 
    const response = Kategori.findAll(
      where: condition,
      include: [ model: db.jenis, as: "umkm_jenis", required: false ],
    );
    const data = await response;
    return res.status(200).send(data);
   catch (error) 
    console.log(error);
    return res.status(500).send(error);
  
;

但是当我尝试从 POSTMAN 访问 API 时,它显示 SequelizeEagerLoadingError。

如果我在 categoriController 上评论了这一行:

  include: [ model: db.jenis, as: "umkm_jenis", required: false ],

然后尝试再次点击 api,它成功显示了我所有的数据。

我已经在这个论坛上阅读了一些类似的问题,但似乎都没有。

感谢您抽出宝贵时间!

更新

下面是models/index.js文件

"use strict";

const fs = require("fs");
const path = require("path");
const Sequelize = require("sequelize");
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || "development";
const config = require(__dirname + "/../config/config.json")[env];
const db = ;

let sequelize;
if (config.use_env_variable) 
  sequelize = new Sequelize(process.env[config.use_env_variable], config);
 else 
  sequelize = new Sequelize(
    config.database,
    config.username,
    config.password,
    config
  );


fs.readdirSync(__dirname)
  .filter((file) => 
    return (
      file.indexOf(".") !== 0 && file !== basename && file.slice(-3) === ".js"
    );
  )
  .forEach((file) => 
    const model = require(path.join(__dirname, file))(
      sequelize,
      Sequelize.DataTypes
    );
    db[model.name] = model;
  );

Object.keys(db).forEach((modelName) => 
  if (db[modelName].associate) 
    db[modelName].associate(db);
  
);

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

db.kategori = require("./umkm_kategori")(sequelize, Sequelize);
db.jenis = require("./umkm_jenis")(sequelize, Sequelize);
db.produk = require("./umkm_produk")(sequelize, Sequelize);
db.review = require("./umkm_review")(sequelize, Sequelize);

module.exports = db;

console.log(错误)

【问题讨论】:

请在您的问题中添加整个错误 SequelizeEagerLoadingError 描述 同时显示models/index 代码 @Anatoly 感谢您的检查,我已经用 index.js 和错误描述更新了问题。 请不要将错误文本包含在屏幕截图中,将其引用为格式化文本。 【参考方案1】:

您已经使用此代码段注册了所有模型和关联:

const model = require(path.join(__dirname, file))(
      sequelize,
      Sequelize.DataTypes
    );
    db[model.name] = model;

Object.keys(db).forEach((modelName) => 
  if (db[modelName].associate) 
    db[modelName].associate(db);
  
);

所以这段代码再次注册模型,只需删除它并使用上面定义的模型名称。

db.kategori = require("./umkm_kategori")(sequelize, Sequelize);
db.jenis = require("./umkm_jenis")(sequelize, Sequelize);
db.produk = require("./umkm_produk")(sequelize, Sequelize);
db.review = require("./umkm_review")(sequelize, Sequelize);

【讨论】:

哦对了!!现在可以了,不知道为什么注册模型两次就不行了? 因为你注册他们没有注册协会 顺便说一句,非常感谢你,我挣扎了 2 天想知道哪里出了问题! 啊,我明白了,再次感谢您。

以上是关于关系表上的NodeJS PostgreSQL Express SequelizeEagerLoadingError的主要内容,如果未能解决你的问题,请参考以下文章

Laravel where() 和 orderBy() 在外部服务器上的关系表上

同一张表上的多个关系

数据类型(字段)表上的雄辩关系

事务隔离级别与表上的锁的关系

多个表上的 MySQL 关系

与关联对象在同一张表上的多对多关系