在 laravel DB::table('mytable')->inset($data) 中复制主键



这是一个典型的情况,当我的应用程序收到150个事务到sametime类型和应用程序崩溃的主键重复

我的问题是,我不能改变列ID整数自动增量,因为我生成这个ID为它是保存ID在"订单"然后将此ID保存在"订单详细信息"中。表,所有是控制器代码

我认为DB::beginTransaction()它会阻塞表,直到完成第一个入站事务,但它不工作.....

是可能的解决方案将实现队列消息,但在这一刻,我不能有这个....的时间我需要一个中间或临时的修复

你知道吗?

特性
  • Laravel 7.0
  • postgres 12
  • 负载试验K6
  • 代码:

DB::beginTransaction();
$id = Orders::withTrashed()->max('id');
$id = $id + 1;
$data["id"] = $id 
.
.
.
DB::table('orders')->insert($data);
for ($x = 0; count($data["details"]) > $x; $x++) {
$data["details"][$x]["id"] = $id;
}
DB::table('orders_details')->insert($data["details"]);
DB::commit();

错误:

to IlluminateDatabaseQueryException: SQLSTATE[23505]: Unique violation: 7 ERROR:  duplicate key value violates unique constraint "order_pkey"

您需要使用自动递增,并像这样使用

$order = new Order();
// Fill the order object
$order->save();
// Now you have order saved. you will have its id. 
// Use that to create details record.
$order_detail = new OrderDetail();
$order_detail->order_id = $order->id;
// Fill rest of the object
$order_detail->save();

如果你仍然不想使用自动递增,而不是使用int的id使用UUID。对于所有行它将是唯一的。

最新更新