Laravel 5.2 数据库迁移和数据填充

一、数据库迁移

Laravel 的数据库迁移提供了对数据库、表、字段、索引的一系列相关操作。下面以创建友情链接表为例。

1. 创建迁移

使用 Artisan 命令  php artisan make:migration create_links_table 

这样就在 database/migrations 目录下生成一个名为 2017_05_06_151645_create_links_table.php 文件。名字的前半段 "2017_05_06_151645_" 是 Laravel 增加的时间戳。后半段 "create_links_table.php" 是表名字。

2. 编写逻辑

然后,打开这个迁移类 2017_05_06_151645_create_links_table.php ,里面有两个方法: up() 和 down() 。up() 方法建表,down() 方法删表。

<?php

use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreateLinksTable extends Migration
{
    /**
     * 执行迁移
     *
     * @return void
     */
    public function up()
    {
        Schema::create('links', function (Blueprint $table){
            $table->engine = 'MyISAM';
            $table->increments('id');
            $table->string('name')->default('')->comment('名称');
            $table->string('title')->default('')->comment('标题');
            $table->string('url')->default('')->comment('地址');
            $table->integer('sort')->default(50)->comment('排序');
        });
    }
    
    /**
     * 回滚迁移
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('links');
    }
}

2017_05_06_151645_create_links_table.php

3. 执行迁移

使用 Artisan 命令  php artisan migrate 

现在,数据库中已经创建了一张 hd_links 表 和 一张记录迁移的表 hd_migrations ("hd_" 是配置的表前缀):

注意:如果手动删除了迁移类并且文件无法重新创建,使用 composer dump-autoload 命令优化一下自动加载就可以重新创建迁移了。

二、数据填充

可用于测试,为数据库中的表填充一些数据。

1. 创建填充

使用 Artisan 命令   php artisan make:seeder LinksTableSeeder 

这将在 database/seeds 目录下生成一个名为 LinksTableSeeder.php 的友情链接填充类。

2. 编写逻辑

然后,打开这个 LinksTableSeeder.php 文件,添加两条测试记录。

<?php

use IlluminateDatabaseSeeder;

class LinksTableSeeder extends Seeder
{
    /**
     * 运行数据库填充
     *
     * @return void
     */
    public function run()
    {
        $data = [
            [
                'name' => 'Laravel 中文社区',
                'title' => 'Laravel China 社区 - 高品质的 Laravel 和 PHP 开发者社区 - Powered by PHPHub',
                'url' => 'https://laravel-china.org/',
                'sort' => '49'
            ],
            [
                'name' => 'GitHub',
                'title' => 'GitHub is where people build software. More than 21 million people use...',
                'url' => 'https://github.com',
                'sort' => '49'
            ]
        ];

        DB::table('links')->insert($data);
    }
}

3. 调用填充

在 database/seeds 目录下的 DatabaseSeeder.php 这个数据库填充类中,在 run() 方法内调用填充。

DatabaseSeeder.php 文件内容:

<?php

use IlluminateDatabaseSeeder;

class DatabaseSeeder extends Seeder
{
    /**
     * 运行数据库填充
     *
     * @return void
     */
    public function run()
    {
        $this->call(LinksTableSeeder::class);
    }
}

4.执行填充

使用 Artisan 命令  php artisan db:seed 

现在,数据库中的 hd_links 表就有了2条记录:

原文地址:https://www.cnblogs.com/mingc/p/6817175.html