V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
hhh798
V2EX  ›  程序员

eggjs 使用 sequelize 的事务无法插入数据

  •  
  •   hhh798 · 2019-09-21 10:26:07 +08:00 · 2249 次点击
    这是一个创建于 1650 天前的主题,其中的信息可能已经有所发展或是发生改变。
    async create(
        userId,
        title,
        content,
        subjectId,
        type,
        categoryId,
        coverImageUrl,
        tags,
        published
      ) {
        const ctx = this.ctx;
        let transaction;
    
        try {
          transaction = await ctx.model.transaction();
    
          const post = await ctx.model.Post.create(
            {
              author_id: userId,
              title,
              content,
              type,
              category_id: categoryId,
              cover_image_url: coverImageUrl,
              subject_id: subjectId,
              published,
              created_at: new Date(),
              updated_at: null,
              deleted_at: null,
              length: 2,
              render_content: "",
              subtitle: "",
              leading_text: ""
            },
            { transaction }
          );
    
          const postId = post && post.getDataValue("id");
    
          if (!postId) {
            throw new Error();
          }
    
          const tagIds = [];
    
          for (const tagName of tags) {
            const result = await ctx.model.Tag.findOrCreate({
              where: { name: tagName },
              transaction
            });
    
            tagIds.push(result[0].dataValues["id"]);
          }
    
          for (const tagId of tagIds) {
            await ctx.model.PostTag.create(
              { post_id: postId, tag_id: tagId },
              { transaction }
            );
          }
    
          await transaction.commit();
    
          return { success: true, data: { postId } };
        } catch (e) {
          console.log(e);
          await transaction.rollback();
          return { success: false, message: "服务器异常" };
        }
      }
    

    没有提示错误,接口可以返回 postId,但查数据库后,数据根本没插进去,请问是什么原因呢?

    3 条回复    2019-09-21 16:48:00 +08:00
    zzyyzz1992
        1
    zzyyzz1992  
       2019-09-21 12:25:45 +08:00
    transaction 需要主动提交
    bi531334444
        2
    bi531334444  
       2019-09-21 13:50:16 +08:00
    之前也遇到过,会不会和数据库引擎有关系?
    hhh798
        3
    hhh798  
    OP
       2019-09-21 16:48:00 +08:00
    @zzyyzz1992 我已经写了:await transaction.commit(); 这个不是主动提交?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3099 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 14:33 · PVG 22:33 · LAX 07:33 · JFK 10:33
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.