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

2019-09-21 10:26:07 +08:00
 hhh798
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,但查数据库后,数据根本没插进去,请问是什么原因呢?

2286 次点击
所在节点    程序员
3 条回复
zzyyzz1992
2019-09-21 12:25:45 +08:00
transaction 需要主动提交
bi531334444
2019-09-21 13:50:16 +08:00
之前也遇到过,会不会和数据库引擎有关系?
hhh798
2019-09-21 16:48:00 +08:00
@zzyyzz1992 我已经写了:await transaction.commit(); 这个不是主动提交?

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/602756

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX