【发布时间】:2022-11-03 13:12:40
【问题描述】:
所以,标题涵盖了很多。 Mycode 一键保存多个项目。假设我们保存食谱或处方(你命名它)。它涵盖了某人需要的药物。我想一键保存它(项目),包括药店的名称。和我的问题是在第二个循环时(在详细的_药物) 它出错了,我需要在数据库中回滚第一个成功的药物.
我的 JSON :
{
"drug_store" : "DRG-2022070001",
"street" : "Mataram Street, Malioboro, Yogyakarta",
"date" : "28-12-2022 12:16:58",
"status" : "RECIPE",
"detailed_drug" : // here detailed_drug
[
{
"drug_id" : "ITM-00001",
"drug_name" : "acyclovir capsule",
"exp_date" : "2022-12-09",
"qty" : "2"
},
{
"drug_id" : "ITM-00001",
"drug_name" : "amiodarone tablet",
"exp_date" : "2022-10-19",
"qty" : "5"
}
]
}
(我已经知道如何保存(药店等)但是当出现错误时(在详细的_药物)我想在数据库中回滚以前成功的数据)
DB::connection('db_name')->beginTransaction();
$detailedRecipe= []; //for drugs or items.
$countDetail = $request->detailed; // lets pretend we have 2 drugs.
for($i=0;$i<$countDetail;$i++){
$data = new Recipe();
$data->drug_name = $request->drug_name;
...
(etc)
...
$success = $data->save();
if(!$success) {
DB::connection('db_name')->rollBack();
return response()->json(['success' => false,'message' => 'Error message ... ']);
}
}
DB::connection('db_name')->commit();
【问题讨论】:
-
当您执行
rollBack()时,它应该回滚从您开始事务时发生的所有事情,其中包括保存在循环中的所有内容。我不清楚究竟是什么问题 -
@apokryfos 在我的数据库中的第一个项目不回滚第二个项目。我写错代码了吗??
-
您能否分享所有代码以及确切的错误消息?
-
@JohnZwarthoed @apokryfos 我解决了我的问题`DB::connection('db_name')` 是我得到错误数据库名称的问题。假设是数据库 B,但我调用数据库 A。感谢您的指导。
标签: laravel eloquent save laravel-9