首页 > 解决方案 > 用事务处理 findAll 查询并使用限制和抵消它的不工作

问题描述

我正在尝试在 sequelize 上使用事务添加分页,但是当我同时添加限制和偏移时,它显示错误为 SequelizeDatabaseError: Invalid column name 'typeId'。

try {
    await sequelize.transaction(async (transaction) => {
        data = await Test.findAll({
          order: [['id', 'DESC']],
          where: { type: 'Y' },
          attributes: ['id', 'type', 'name'],
          include: [
            {
                model: xyz,
                as: 'xyz',
                attributes: ['id'],
                include: {
                    model: efg,
                    as: 'efg',
                    attributes: ['id', 'typeId'],
                },
            },
            {
                model: abc,
                as: 'abc',
                attributes: ['id'],
                include: {
                    model: ijk,
                    as: 'ijk',
                    attributes: ['id', 'name'],
                },
            }
          ],
          transaction,
          limit: 10,
          offset: 0,
        }).then(res=>{
          return res;
        })
      });
} catch(e) {

}

任何建议将不胜感激。谢谢!

标签: mysqlsqlnode.jssequelize.jssequelize-typescript

解决方案


您需要将交易作为第二个参数,如下所示 -

try {
    await sequelize.transaction(async (transaction) => {
        data = await Test.findAll({
          order: [['id', 'DESC']],
          where: { type: 'Y' },
          attributes: ['id', 'type', 'name'],
          include: [
            {
                model: xyz,
                as: 'xyz',
                attributes: ['id'],
                include: {
                    model: efg,
                    as: 'efg',
                    attributes: ['id', 'typeId'],
                },
            },
            {
                model: abc,
                as: 'abc',
                attributes: ['id'],
                include: {
                    model: ijk,
                    as: 'ijk',
                    attributes: ['id', 'name'],
                },
            }
          ],
          // comment the line below
          // transaction,
          limit: 10,
          offset: 0,
        },
        { transaction }
        ).then(res=>{
          return res;
        })
      });
} catch(e) {

}

我知道官方文档描述了按照您实现的方式执行方法的事务,findAll但是在我尝试的情况下并没有按预期工作。


推荐阅读