encountered problems with data padding, which was previously populated with random data, using laravel model factory and Faker\ Generator
to generate random data. It"s very convenient. But I want to fill in some data provided by me instead of random data when the program is initialized.
suppose: the data I provide is $name
. I have two tables, categories
and navigations
. There is an association between the two tables, and navigations.category_id
corresponds to categories.id
. My idea is shown in the code, although I can successfully write the data, but it doesn"t feel good, thanks to the bosses for their ideas.
the code is as follows:
<?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class CategoryTableSeeder extends Seeder
{
protected $name = [
"php" => [
[
"name" => "php1",
"describe" => "php1",
"icon" => "php1"
], [
"name" => "php1",
"describe" => "php1",
"icon" => "php1"
], [
"name" => "php1",
"describe" => "php1",
"icon" => "php1"
],
], "mysql" => [
[
"name" => "mysql1",
"describe" => "mysql1",
"icon" => "mysql1"
], [
"name" => "mysql1",
"describe" => "mysql1",
"icon" => "mysql1"
], [
"name" => "mysql1",
"describe" => "mysql1",
"icon" => "mysql1"
],
], "vue" => [
[
"name" => "vue1",
"describe" => "vue1",
"icon" => "vue1"
], [
"name" => "vue1",
"describe" => "vue1",
"icon" => "vue1"
], [
"name" => "vue1",
"describe" => "vue1",
"icon" => "vue1"
], [
"name" => "vue1",
"describe" => "vue1",
"icon" => "vue1"
], [
"name" => "vue1",
"describe" => "vue1",
"icon" => "vue1"
],
],
];
/**
* Run the database seeds.
*
* @return void
*/
public function run ()
{
foreach ($this->name as $key => $value) {
$id = DB::table("categories")->insertGetId([
"name" => $key,
"type" => "1",
"created_at" => \Carbon\Carbon::now()->toDateTimeString(),
"updated_at" => \Carbon\Carbon::now()->toDateTimeString(),
]);
foreach ($value as $k => $v) {
DB::table("navigations")->insert([
"category_id" => $id,
"name" => $v["name"],
"describe" => $v["describe"],
"icon" => $v["icon"],
"created_at" => \Carbon\Carbon::now()->toDateTimeString(),
"updated_at" => \Carbon\Carbon::now()->toDateTimeString(),
]);
}
}
}
}