在 Laravel 中使用 updateOrCreate 进行多数据插入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27106825/
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
Using updateOrCreate for multiple data insert in Laravel
提问by Ronser
I have used the following insert arrayto insert multiple entries in LaravelEloquent ORM
我使用以下插入数组在Laravel 中插入多个条目Eloquent ORM
$i = 0;
foreach($exerciseValArray as $kkey=>$exerciseValue){
if($exerciseValue['exercise'] =='' || $exerciseValue['section_type'] == ''){
return Response::JSON(array('errors'=>array('Error in workout exercise section')));
}
$exerciseData = explode(',',$exerciseValue['exercise']);
foreach($exerciseData as $exerciseid){
$insertArray[$i]['fk_workouts_id'] = $id;
$insertArray[$i]['fk_users_id'] = $userId;
$insertArray[$i]['fk_exercises_id']= $exerciseid;
$insertArray[$i]['section'] = $exerciseValue['section_type'];
$insertArray[$i]['status'] = 1;
$insertArray[$i]['item_index'] = $index+$kkey+1;
$insertArray[$i]['updated_at'] = $workoutDetails['updated_at'];
$i++;
}
}
WorkoutExercise::insert($insertArray);
The above code works fine and inserts the data array in to the database.
上面的代码工作正常并将数据数组插入到数据库中。
I have learnt the usage of Model::updateOrCreate
and used it in some of my modules successfully (i.e)
我已经成功地学习了Model::updateOrCreate
它的用法并在我的一些模块中使用了它(即)
Model::updateOrCreate($attributes = array('key' => 'value'), $values = array('key' => 'value'));
My question is how to edit the above insert snippet so that I could use Model::updateOrCreate
in it. My $attributes
fields are 'fk_workouts_id','fk_users_id','fk_exercises_id' and the rest in the $values
to be changed.
我的问题是如何编辑上面的插入片段以便我可以Model::updateOrCreate
在其中使用。我的$attributes
字段是 'fk_workouts_id', 'fk_users_id', 'fk_exercises_id' 和其余的$values
要更改。
I have no idea how to implement this. Pls help...
我不知道如何实现这一点。请帮助...
回答by Satish Shinde
You can try like,
你可以试试,
First Way
第一种方式
$user = User::firstOrNew(array('name' => 'satish'));
$user->field = 'value';
$user->save();
It will check for user name=satish
if found then return it. If not found then create new and return. Then you can set field values.
name=satish
如果找到,它将检查用户,然后返回它。如果没有找到,则创建新的并返回。然后您可以设置字段值。
Check this link. http://laravel.com/docs/4.2/eloquent#insert-update-delete
检查此链接。 http://laravel.com/docs/4.2/eloquent#insert-update-delete
Second WayMannually Check record is exists.
第二种方式手动检查记录是否存在。
$arr=array('field'=>"value");
$row = User::find($id);
if ($row === null) {
//Insert your record
} else {
//update your record
}
UPDATED
更新
You can also use updateOrCreate
- update an existing model or create a new model if none exists. updateOrCreate
persists the model, so there's no need to call save()
.
您还可以使用updateOrCreate
- 更新现有模型或创建新模型(如果不存在)。updateOrCreate
保留模型,因此无需调用 save()
.
Example-
例子-
// If there's a flight from Oakland to San Diego, set the price to .
// If no matching model exists, create one.
$flight = App\Flight::updateOrCreate(
['departure' => 'Oakland', 'destination' => 'San Diego'],
['price' => 99]
);
回答by Neo
I think you are working with the customized framework of laravel so you have UpdateOrCreate method because laravel not provides such methods if my assumption is true than below written code may b useful for your application
我认为您正在使用 laravel 的自定义框架,因此您有 UpdateOrCreate 方法,因为如果我的假设成立,laravel 不提供此类方法,那么下面编写的代码可能对您的应用程序有用
foreach($exerciseValArray as $kkey=>$exerciseValue){
if($exerciseValue['exercise'] =='' || $exerciseValue['section_type'] == ''){
return Response::JSON(array('errors'=>array('Error in workout exercise section')));
}
$exerciseData = explode(',',$exerciseValue['exercise']);
$attr_array = array('fk_workouts_id','fk_users_id','fk_exercises_id','section','status','item_index','updated_at');
foreach($exerciseData as $exerciseid){
$val_array = array($userId,$exerciseid,$exerciseValue['section_type'],1,$item_index,$workoutDetails['updated_at']);
WorkoutExercise::updateOrCreate($attr_array,$val_array);
}
}
But if you are not using such kind of customized framework than please try with the below code it may work fine
但是,如果您没有使用这种自定义框架,请尝试使用以下代码,它可能会正常工作
foreach($exerciseValArray as $kkey=>$exerciseValue){
if($exerciseValue['exercise'] =='' || $exerciseValue['section_type'] == ''){
return Response::JSON(array('errors'=>array('Error in workout exercise section')));
}
$exerciseData = explode(',',$exerciseValue['exercise']);
foreach($exerciseData as $exerciseid){
$item_index = $index+$kkey+1;
// Retrieve the record by the fk_workouts_id, or create it if it doesn't exist...
$exercise = WorkoutExercise::firstOrCreate($attributes = array('fk_workouts_id' => $id));
/* assign the values of other fields to store in database table*/
$exercise->fk_users_id = $userId;
$exercise->fk_exercises_id = $exerciseid;
$exercise->section = $exerciseValue['section_type'];
$exercise->status = 1;
$exercise->item_index = $item_index;
$exercise->updated_at = $workoutDetails['updated_at'];
$exercise->save(); // update the record
}
}
good luck...:)
祝你好运...:)