Skip to content

Instantly share code, notes, and snippets.

@fakeheal
Last active October 5, 2016 10:37
Show Gist options
  • Save fakeheal/140545a1954b8852a43f5d1c67f3fc19 to your computer and use it in GitHub Desktop.
Save fakeheal/140545a1954b8852a43f5d1c67f3fc19 to your computer and use it in GitHub Desktop.
<?php
use Carbon\Carbon;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class CategoryProductTable extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$products = \App\Product::all();
//Categories that don't have child categories.
$categories = \App\Category::where('id', '!=', 'sub_category_id')->get();
foreach ($products as $product) {
DB::table('category_product')->insert([
'category_id' => $categories->random()->id,
'product_id' => $product->id,
'created_at' => Carbon::now()->format('Y-m-d H:i:s')
]);
}
}
}
<?php
use Carbon\Carbon;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class CategoryTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
/**
* We are going to insert 100 categories.
*/
$faker = Faker\Factory::create();
for ($i = 0; $i < 100; $i++) {
DB::table('categories')->insert([
'name' => implode($faker->words(),' '),
'sub_category_id' => (($i % 2) === 0) ? $this->get_random_category_id() : null,
'created_at' => Carbon::now()->format('Y-m-d H:i:s')
]);
}
}
private function get_random_category_id()
{
$random_category = \App\Category::inRandomOrder()->first();
return !is_null($random_category) ? $random_category->id : null;
}
}
<?php
use Carbon\Carbon;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class ProductTableSeeder extends Seeder
{
public function run()
{
/**
* We are going to insert 500 products.
*/
$faker = Faker\Factory::create();
for ($i = 0; $i < 500; $i++) {
DB::table('products')->insert([
'name' => implode($faker->words(),' '),
'description' => $faker->paragraph(),
'price' => $this->mt_rand_float(0, 100),
'created_at' => Carbon::now()->format('Y-m-d H:i:s')
]);
}
}
//Thanks to: http://stackoverflow.com/a/38691102/867418
private function mt_rand_float($min, $max, $countZero = '0')
{
$countZero = +('1' . $countZero);
$min = floor($min * $countZero);
$max = floor($max * $countZero);
$rand = mt_rand($min, $max) / $countZero;
return $rand;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment