最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

为什么我的knex事务抛出:参考错误:未定义

网站源码admin18浏览0评论

为什么我的knex事务抛出:参考错误:
未定义

为什么我的knex事务抛出:参考错误: 未定义

我正在使用交易方法完成我的第一个knex交易。目的是使三个插入语句的集合以原子方式将传入记录的数据持久保存到三个表中。对于上下文-传入的记录代表具有两个1:M子关系的父对象-“材料具有0到许多属性,而材料具有0到许多音符。”所以我有一个材料关系,一个material_properties关系和一个material_notes关系。

我有一个不在事务内的方法版本。但是,当我尝试在Knex documentation - 'Transaction' section中指定的事务中包装功能时,在“与上述示例相同,使用另一种await / async方法:”小节中,我收到一个参考错误,即第一个子关系不是定义。另外,我得到一个

UnhandledPromiseRejectionWarning:ReferenceError:未定义trx

注意:父表被插入到第一个表中,并且尝试插入第一个子表时出现参考错误:'material_properties'。

这是有效的方法:

const materialRecord = {
            name: material.name,
            description: material.description ? material.description : null,
            user_id: userId
        }

/** 
 * Insert primary material into materials & get id value for FK
 */
const materialPrimaryKeyArray = await knex('materials')
  .returning('id')
  .insert(materialRecord)
  .catch(error => console.error(`Unable to persist record, ${error}`)) 
const materialPrimaryKey = materialPrimaryKeyArray[0];

/**
 * Persist properties and/or notes if they exist
 */
if (material.materialProperties) {
  material.materialProperties.forEach(property => {
    property['material_id'] = materialPrimaryKey
  });
  knex('material_properties')
    .returning('id')
    .insert(material.materialProperties)
    .catch(error => console.error(`Unable to persist record, ${error}`)) 
};

if (material.materialNotes) {
  material.materialNotes.forEach(note => {
    note['material_id'] = materialPrimaryKey
  });
  knex('material_notes')
    .returning('id')
    .insert(material.materialNotes)
    .catch(error => console.error(`Unable to persist record, ${error}`)) 
   };
   
return materialPrimaryKey;
回答如下:

您正在尝试访问其范围之外的trx变量。

} catch (error) {
  console.error(`Unable to persist data, ${error}`)
  trx.rollback // here you are trying to use undefined variable
}

您可以删除该行。由于knex.transaction(async trx => {})引发错误,因此交易会自动回滚(因为处理程序功能正在重新调整承诺)。

也只访问函数而不调用它trx.rollbacktrx.rollback()不会做任何事情。

发布评论

评论列表(0)

  1. 暂无评论