[英]Laravel 5.2 execute multiple db transactions then commit or rollback if failed
我正在學習Laravel,正在研究5.22。 我試圖將兩個記錄保存到兩個表中,但是僅在兩個方面都成功的情況下才提交更改,否則我希望它失敗並回滾。
保存的我的控制器代碼是:
public function store(Request $request)
{
$all = $request->all();
// we need to fill in who is the creator of this new user,
$all['creator_user_id'] = Auth::user()->id;
// Commit both updates or fail and rollback
DB::transaction(function ($all) {
$client = Client::create($all);
$orgClient['organisation_id'] = $client->organisation_id;
$orgClient['client_id'] = $client->client_id;
OrganisationClient::create($orgClient);
});
return redirect()
->route('client.index')
->withMessage([
'type' => 'success',
'value' => 'Client <strong>' . $all->client_name . '</strong> successfully created.']);
}
失敗並顯示以下錯誤:
Type error: Argument 1 passed to Illuminate\Database\Eloquent\Model::create() must be of the type array, object given, called in /home/vagrant/Code/simply-invoice/app/Http/Controllers/ClientController.php on line 80
我的問題似乎是將$all
傳遞給了閉包。 如果我從閉合參數中刪除$all
,那么我將得到undefined variable all
。 我該怎么做呢? 謝謝!
您將$all
設置為回調參數,而不use
它。 transaction
回調當前正在接收Illuminate\\Database\\Connection
的實例作為參數。
為了獲得實際的變量,您需要將回調更改為此:
// ....
DB::transaction(function () use($all) {
// ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.