Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using updateOrCreate for multiple data insert in Laravel

I have used the following insert array to insert multiple entries in 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($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.

I have no idea how to implement this. Pls help...

like image 363
Ronser Avatar asked Nov 24 '14 14:11

Ronser


2 Answers

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.

Check this link. http://laravel.com/docs/4.2/eloquent#insert-update-delete

Second Way Mannually 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().

Example-

// If there's a flight from Oakland to San Diego, set the price to $99.
// If no matching model exists, create one.
$flight = App\Flight::updateOrCreate(
    ['departure' => 'Oakland', 'destination' => 'San Diego'],
    ['price' => 99]
);
like image 82
Satish Shinde Avatar answered Oct 21 '22 02:10

Satish Shinde


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

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...:)

like image 30
Neo Avatar answered Oct 21 '22 03:10

Neo