创建表和填充数据
基于类图创建数据库表
Laravel提供了Artisan命令行工具,可以快速创建数据库表并且留存建表文件。
上一节文章已经创建出了类图,可以根据类图中的类节点建表文件。
例子:创建Project的Migration文件
在项目的根目录下运行一下命令:
php artisan make:migration CreateProjectsTable
运行完这个命令后,就会发现,database/migrations/2020_05_31_080922_create_projects_table.php文件,已经创建。
编辑这个文件,提供建表信息。
class CreateProjectsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('projects', function (Blueprint $table) {
$table->id();
$table->integer( 'flow_id' )->default( 0 )->unsigned()->index();
$table->integer( 'owner_id' )->unsigned()->index();
$table->string( 'owner_name', 100 );
$table->string( "name", "100" );
$table->string( "description", "500" );
$table->timestamp( "deadline" )->nullable(false);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('projects');
}
}
运行Migration
编辑好所有Migration文件后,可以运行laravel提供的命令,生成数据库表。(需要先设置好数据库连接配置)
php artisan migrate:fresh
填充数据库表
例子:创建Seeder文件
在项目的根目录下运行一下命令:
php artisan make:seeder InitSeeder
运行完这个命令后,就会发现,database/seeds/InitSeeder.php文件,已经创建。
编辑这个文件,提供填充的数据。
<?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Collection;
use App\Models\FlowProcess;
use App\Models\Task;
class InitSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run(){
$userCollection = factory( \App\User::class, 15 )->create();
$userCollection->first()->name = 'zhangsan';
$userCollection->first()->email = 'zhangsan@zhangsan.com';
$userCollection->first()->password = Hash::make('zhangsan');
/**
* @var \App\Models\Project $project
*/
$project = factory( \App\Models\Project::class, 1 )->make()->first();
$project->owner_id = $userCollection->first()->id;
$project->owner_name = $userCollection->first()->name;
$project->flow_id = 0;
$project->save();
//
$project->members()->saveMany( $userCollection );
...
}
...
运行Seeder
运行完一下命令后,数据库对应的表中,已经存在相应的数据了。
php artisan db:seed
732

被折叠的 条评论
为什么被折叠?



