Skip to content

Instantly share code, notes, and snippets.

@tisuchi
Created July 26, 2019 15:57
Show Gist options
  • Save tisuchi/6e25b21bec8b0a36fba7ec02dc13f3ab to your computer and use it in GitHub Desktop.
Save tisuchi/6e25b21bec8b0a36fba7ec02dc13f3ab to your computer and use it in GitHub Desktop.
Reduce Parent and Child Loop
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class TestController extends Controller
{
public function index()
{
$lastId = $this->getTheLastIdFromTheTable();
foreach (range(1,10) as $value) {
++$lastId; // every time the last ID will be increased by 1
/**
* keep your parent data like this-
*
* $parent = new Model();
* $parent->field = "Some Data";
* $parent->field = "Some Data";
* $parent->field = "Some Data";
*/
$parrentData = [
'some_parrent_key' => 'some parrent value',
'some_parrent_key' => 'some parrent value',
'parrent_id' => $lastId
];
echo "<br/> parrent ID is: " . $lastId . "<br/>";
// set a flag
$doesChildInserted = false;
foreach (range(1,20) as $innerValue) {
$data = [
'some_key' => 'some value',
'parrent_id' => $parrentData['parrent_id'],
];
if ($data) {
// change flag
$doesChildInserted = true;
}
echo "Inserted Child Data <br/>";
}
if ( $doesChildInserted ) {
// now save parrentData with a ->save() method.
}
echo "========================================";
}
}
public function getTheLastIdFromTheTable()
{
// getting the last ID from the table
return 121;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment