Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Seeder Pivot Seeder
<?php
use Guiaa\Models\Segments;
use Guiaa\Models\SegmentTags;
use Guiaa\Models\Tags;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class SegmentTagsSeeder extends Seeder
{
private $pivotData = [];
private $totalValues = 107;
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
SegmentTags::truncate();
for ($x = 1; $x <= $this->totalValues; $x++) {
$new_pivot_value = self::newPivot();
array_push($this->pivotData, $new_pivot_value);
DB::table('segments_tags')->insert([
'segment_id' => $new_pivot_value[0],
'tag_id' => $new_pivot_value[1]
]);
}
}
function newPivot(){
$pivot_value = self::getData();
$result = self::in_array_r($pivot_value, $this->pivotData);
/*
* If its a duplicate then re-run method
*
*/
if($result) return self::newPivot();
return $pivot_value;
}
function getData(){
$faker = Faker\Factory::create();
$segments_id = $faker->randomElement(Segments::pluck('id')->toArray());
$tags_id = $faker->randomElement(Tags::pluck('id')->toArray());
return [
(Int)$segments_id,
(Int)$tags_id
];
}
function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item)
&& self::in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.