1

I want to replicate multiple relational rows to the same table with the diff job id. But it doesn't work.

Here is my code

$parentJobUnits = Unit::where('job_id',$jobId)->get();  //may be single or multiple rows for units.

$JobCopy = $job->replicate()->save();    //main job copied for new units.

$partsCopy = array_map(function(Unit $unit) use($JobCopy)
{

     $newUnit = $unit->replicate();
     $newUnit->job_id = $JobCopy->id;
     return $newUnit->save();

}, $parentJobUnits);

The above code is not working for multiple row replication.

Mujahid Bhoraniya
  • 1,518
  • 10
  • 22
kinjal jethva
  • 249
  • 2
  • 6
  • 18

3 Answers3

3

Try removing the save method which causes a true return and not the copied record

correct: $job->replicate();
incorrect: $job->replicate()->save();

otherwise I'd do something like...

$parentJobUnits = Unit::where('job_id',$jobId)->get();

foreach($parentJobUnits as $unit)
{
    $unit->replicate()->save();
}
David Buck
  • 3,752
  • 35
  • 31
  • 35
0
$CollageData= Collage::where('student_id',$student_id)->get();
foreach($CollageData as $key => $collage )
   {     
      $collage->replicate()->save();
     
   }

This Works for me.

-1

replicate() function does not work on get() function. It only works with find() function.

$parentJobUnits = Unit::where('job_id',$jobId)->get();

foreach($parentJobUnits as $key => $value)
{
    $new_unit = Unit::find($value->id)->replicate(); // $value->id is your primary key
    $new_unit->save();
}

It will replicate the multiple rows.

mybrave
  • 1,662
  • 3
  • 20
  • 37
Sohail Ansari
  • 350
  • 4
  • 10