Laravel 复制记录并用新值复制
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34257741/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel Copy record and duplicate with new values
提问by Tupic
How can i copy a record and save it with a different value for 1 or more field?
如何复制记录并将其保存为 1 个或多个字段的不同值?
for example: get----> first_name, last_name, civil_status, work
例如:get---->名字,姓氏,civil_status,工作
i want to copy the first name, and last name then insert it with a new civil status and work.
我想复制名字和姓氏,然后将其插入新的公民身份和工作。
回答by Pantelis Peslis
You could use the replicate
method of model like this:
您可以replicate
像这样使用模型方法:
// Retrieve the first task
$task = Task::first();
$newTask = $task->replicate();
$newTask->project_id = 16; // the new project_id
$newTask->save();
回答by Miguel Oliveira
You could use replicate
method. This will create a new object with the same values except the primary key, and the timestamps. After that you can save your model:
你可以使用replicate
方法。这将创建一个具有相同值的新对象,除了主键和时间戳。之后,您可以保存模型:
$task = Task::find(1);
$new = $task->replicate();
If you want you could change a property
如果你愿意,你可以改变一个属性
$new->project = $otherProject;
and then
进而
$new->save();
if you want the new ID, easy:
如果你想要新的 ID,很简单:
$newID = $new->id;
回答by Alex
You can use replicate()
and then update that row:
您可以使用replicate()
然后更新该行:
Model::find(1)->replicate()->save();
$model = Model::find(1);
$model->project_id = $new_project_id;
$model->save();