eggjs使用sequelize的事务无法插入数据
发布于 5 年前 作者 wuyugege 4993 次浏览 来自 问答

代码如下:

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,但查数据库后,数据根本没插进去,请问是什么原因呢?

5 回复

提交么成功?

@waitingsong 应该没成功,但是并没有提示错误,接口正常返回了postID。我试了下不用事务,可以正常插入数据

@wuyugege 我需要问你个问题,我按照EGG官方引入了sequelize后,创建模型时也指定了主键autoIncrement,插入数据的时候却不会自动增长。报错Duplicate entry ‘0’ for key ‘PRIMARY’, 你有遇到吗

@gejigejigeji 这个没有遇到过,你最好上点代码

model/User.js 1.png

controller/home.js 2.png

基本上和官网一样没有改动,创建数据库表是使用sequelize.model.sync()方法来创建的,用navicate for mysql查看表也是能看到主键ID自动增长的。 但是使用sequelize.model.create()方法插入数据的时候就会报错Duplicate entry ‘0’ for key ‘PRIMARY’,原因是主键id一直都是0,主键重复导致的。

回到顶部