如果我的查询有错误,我想知道如何使用事务查询来回滚,如果没有错误,则要提交。我的查询使用foreach
导致多个数据。这就是我正在尝试的。
DB::transaction(function(){
$receiving = New Table1;
$receiving->created_on = \Carbon\Carbon::now();
$receiving->created_by = Auth::user()->id;
$receiving->received_on = \Carbon\Carbon::parse($request->DateAcquired);
$receiving->received_by = Auth::user()->id;
$receiving->checked_on = \Carbon\Carbon::now();
$receiving->checked_by = Auth::user()->id;
$receiving->remark = $request->Remarks;
$receiving->save();
foreach ($request->data as $data)
{
$asset = New Table2;
$asset->category = $data[0];
/*$asset->asset_number = $data[1];*/
$asset->name = $data[2];
$asset->brand = $data[3];
$asset->model = $data[4];
$asset->ownership_type = $data[5];
$asset->serial_number = $data[6];
$asset->mac_address = $data[7];
$asset->cpu = $data[8];
$asset->memory = $data[9];
$asset->hard_disk = $data[10];
$asset->os = $data[11];
$asset->remark = $data[12];
$asset->description = $data[13];
$asset->date_acquired = \Carbon\Carbon::parse($request->DateAcquired);
$asset->receiving_id = $receiving->id;
$asset->save();
}
});
我也尝试使用DB::beginTransaction();
但是我遇到了一个错误
查询生成器中未定义的beginTransaction()函数。
答案 0 :(得分:1)
如Laravel Database Transactions中所述:
您可以在DB Facade上使用事务方法来运行一组 数据库事务中的操作。如果抛出异常 在交易关闭内,交易将自动进行 回滚。如果关闭成功执行,则交易 将自动提交。你不用担心 使用事务时手动回滚或提交 方法:
但是正如我在您的代码中看到的那样,您正在$request
的回调函数中使用transaction
变量,因此,此时,您应该将$request
传递给回调函数使用它。
您的代码如下:
DB::transaction(function() use ($request) {
// put your code here
});
答案 1 :(得分:0)
您可能需要通过use()
DB::transaction(function() use ($request) {
$receiving = New Table1;
$receiving->created_on = \Carbon\Carbon::now();
$receiving->created_by = Auth::user()->id;
$receiving->received_on = \Carbon\Carbon::parse($request->DateAcquired);
$receiving->received_by = Auth::user()->id;
$receiving->checked_on = \Carbon\Carbon::now();
$receiving->checked_by = Auth::user()->id;
$receiving->remark = $request->Remarks;
$receiving->save();
foreach ($request->data as $data)
{
$asset = New Table2;
$asset->category = $data[0];
/*$asset->asset_number = $data[1];*/
$asset->name = $data[2];
$asset->brand = $data[3];
$asset->model = $data[4];
$asset->ownership_type = $data[5];
$asset->serial_number = $data[6];
$asset->mac_address = $data[7];
$asset->cpu = $data[8];
$asset->memory = $data[9];
$asset->hard_disk = $data[10];
$asset->os = $data[11];
$asset->remark = $data[12];
$asset->description = $data[13];
$asset->date_acquired = \Carbon\Carbon::parse($request->DateAcquired);
$asset->receiving_id = $receiving->id;
$asset->save();
}
});