简体   繁体   English

如何在AdonisJS中使用交易?

[英]How to use Transactions in AdonisJS?

I've been trying to implement a simple transaction in Adonis. 我一直在尝试在Adonis中实现一个简单的事务。

The scenario is I have a table that has a unique field named name and want to rollback the transaction of a multiple create query when one of the items name exists. 方案是我有一个表具有名为name的唯一字段,并且当其中一个项name存在时,想要回滚多个创建查询的事务。

const Product = use('App/Models/Product')
const Database = use('Database')

const data = [
  {
    name: 'name1'
  },
  {
    name: 'name2'
  },
  {
    name: 'name3'
  },
  {
    name: 'name4'
  }
]

const trx = await Database.beginTransaction()

try {
  await Product.createMany(data, trx)
  await trx.commit()
  return response.json({
    success: true
  })
} catch (e) {
  await trx.rollback()
  return response.json({
    success: false
  })
}

In the code above, products name2, name3, name4 exists and name1 is not. 在上面的代码中,产品name2,name3,name4存在而name1不存在。 So now we assume that when it starts creating name2, it will throw an error and rollback the transaction. 所以现在我们假设当它开始创建name2时,它会抛出一个错误并回滚事务。

But it didn't. 但事实并非如此。 name1 is still inserted and not rolled back. name1仍然插入但未回滚。

Also tried 也试过了

try {
  await Database.transaction(async (trx) => {
    await trx.insert(data).into('products')
  });
} catch (e) {}

But got the same output. 但得到了相同的输出。

I am using mysql 5.5 by the way. 我顺便使用mysql 5.5。

Am I missing something here? 我在这里错过了什么吗?

If i correctly understood your question, you dont want to save duplicate rows in the database. 如果我正确理解了您的问题,您不希望在数据库中保存重复的行。 for this purpose just change your Product migration file like this and add unique option to name colume. 为此,只需更改此类产品迁移文件,并为name colume添加唯一选项。

'use strict'
/** @type {import('@adonisjs/lucid/src/Schema')} */
const Schema = use('Schema')


class ProductsSchema extends Schema {
  up() {
    this.create('products', (table) => {
      table.increments()
      table.string('name').unique()
      table.timestamps()
    })
  }

  down() {
    this.drop('products')
  }
}


module.exports = ProductsSchema

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM