【问题标题】:Laravel 8 how to replicate and get id of new modelLaravel 8 如何复制和获取新模型的 id
【发布时间】:2022-11-10 16:44:37
【问题描述】:
我正在使用 laravel,我想复制一些数据。所以我这样做了:
$id = $request->id;
$data = Setting::find($id);
$newSetting = $data->replicate()->save();
但是如何获得 id 的 $newSetting 呢?为了保存该返回值,我需要返回我的新id。我尝试用 push 代替 save 但这也是返回的。
我检查了文档,但找不到。
有人可以帮我吗?
提前致谢。
【问题讨论】:
标签:
laravel
eloquent
laravel-8
【解决方案1】:
你只需要:
$id = $request->id;
$data = Setting::find($id);
// now replicate data and save
$newData = $data->replicate();
//save the new data
$newData->save();
//get the new id
$newId = $newData->id;
【解决方案2】:
可以这样做:
$id = $request->id;
$data = Setting::find($id);
// replicate
$replicatedData = $data->replicate();
// get convert the model collection to array
$arrayReplicatedData $replicatedData->toArray();
//save it with the create method
$newCreatedModel = Setting::create($arrayReplicatedData);
// Get the new id
$newId = $newCreatedModel->id;