Laravel数据库迁移和填充(支持中文)

写在前面

经常我们做项目都团队协作开发,每个人都在自己本地的数据库,如果你曾经出现过让同事手动在数据库结构中添加字段的情况,数据库迁移可以解决你这个问题。

不仅如此,在线上部署的时候,也避免了手动导入数据库或手动修改数据结构的麻烦,数据迁移帮你方便的维护着数据结构。

数据填充,让我们测试的时候需要大量的假数据不再一条一条的去造数据,可以轻松的批量填充大量数据。

本文基于Laravel5.5,其他版本大同小异。

数据迁移

假如我们需要一张学生表,我们不再使用原生SQl语句去创建表。

创建迁移文件

前提是已经配置好了数据库连接信息

php artisan make:migration create_students_table

此命令会在database/migrations/目录生成类似2017_10_28_035802_create_students_table.php的文件

我们在里边添加students表的数据结构

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateStudentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        // students为表名称
        Schema::create('students', function (Blueprint $table) {
            // 存储引擎
            $table->engine = 'InnoDB';
            // id自增
            $table->increments('id');
            // 学生名称
            $table->string('name');
            // 性别
            $table->string('sex');
            // 邮箱
            $table->string('email');
            // 喜爱的颜色
            $table->string('favorite_color');
            // 手机号
            $table->string('phone');
            // 地址
            $table->string('addr');
            // 自动维护时间戳
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('students');
    }
}

更多用法,请参考官方手册。

运行迁移
php artisan migrate

这样会运行database/migrations/目录的所有迁移文件,并自动创建migrations表,来记录已经运行过的迁移文件,防止重复运行。
我们看一下数据库是不是自动创建了students表了呢。

如果出现以下错误:

[Illuminate\Database\QueryException]
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was t
oo long; max key length is 767 bytes (SQL: alter table users add unique users_email_unique(email))

[PDOException]
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was t
oo long; max key length is 767 bytes

在database/migrations/目录里会有laravel自带的用户和重置密码的两个迁移文件,会一并运行。
在这里我们这样解决,修改数据库配置文件config/database.php里的mysql下的字符集为utf8即可

'charset'     => 'utf8',
'collation'   => 'utf8_unicode_ci',

想知道为什么,可猛戳 https://segmentfault.com/a/1190000008416200

数据填充(支持中文)
创建学生表Eloquent模型

在app目录下创建Student.php

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

/**
 * 学生模型
 */
class Student extends Model
{

}
创建填充文件
php artisan make:seed StudentsTableSeeder

这条命令会在database/seeds/目录下生成StudentsTableSeeder.php填充文件

<?php

use Illuminate\Database\Seeder;

class StudentsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // 调用模型工厂 生成10000条数据
        factory(App\Student::class, 10000)->create();
    }
}
调用该 Seeders

我们打开database/seeds/DatabaseSeeder.php文件,修改为

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // 调用学生表填充文件
        $this->call(StudentsTableSeeder::class);
    }
}
创建 模型工厂 填充
php artisan make:factory StudentsFactory -m Student

此命令会在database/factories/目录下生成StudentsFactory.php文件,我们定义一下要填充的数据格式

<?php

use Faker\Generator as Faker;

/* @var Illuminate\Database\Eloquent\Factory $factory */

$factory->define(App\Student::class, function (Faker $faker) {
    $sex = rand(1, 1000);
    return [
        'name'           => $faker->name,
        'sex'            => $sex % 2 == 0 ? '男' : '女',
        'email'          => $faker->unique()->safeEmail,
        'favorite_color' => $faker->safeColorName,
        'phone'          => $faker->phoneNumber,
        'addr'           => $faker->address,
    ];
});

更多配置请查阅 vendor/fzaninotto/faker/src/Faker/Generator.php文件

让faker填充中文

在app/Providers/AppServiceProvider.php的boot()中添加:

    public function boot()
    {
        // 填充中文数据
        $this->app->singleton(\Faker\Generator::class, function () {
            return \Faker\Factory::create('zh_CN');
        });
    }
开始填充

首先我们执行一下:

composer dump-autoload

自动加载一下我们在database/seeds/目录创建的填充文件,以避免出现以下错误:

[ReflectionException]
Class StudentsTableSeeder does not exist

接着我们运行填充命令:

php artisan db:seed

由于我们填充的是一万条数据,可以时间稍长,可以刷新数据库看着逐条增加的数据。

大功告成

如果以上操作都没有报错的话,来看一下我们的数据库表students表是否有数据了呢?

idnamesexemailfavorite_colorphoneaddrcreated_atupdated_at
10000谈英cum_et@example.com白色17642207316贵阳海陵区2017-10-28 05:19:102017-10-28 05:19:10
9999汤淑珍qlaudantium@example.net黑色18239453935南宁友好区2017-10-28 05:19:102017-10-28 05:19:10
9998贾春梅ea35@example.com粟色17103645128长沙萧山区2017-10-28 05:19:102017-10-28 05:19:10
9997季志明cdeleniti@example.com灰色17002359608天津花溪区2017-10-28 05:19:102017-10-28 05:19:10
9996成燕aspernatur.aut@example.com黄色17181193397贵阳锡山区 2017-10-28 05:19:102017-10-28 05:19:10
9995米博reprehenderit_autem@example.com17187328893广州东丽区2017-10-28 05:19:102017-10-28 05:19:10
9994兰淑兰et_ea@example.com绿色18592254358兰州经济开发新区2017-10-28 05:19:102017-10-28 05:19:10
9993乐瑶vel.vitae@example.org藏青15891490007香港龙潭区 2017-10-28 05:19:102017-10-28 05:19:10
9992叶志新lcumque@example.net藏青15564391466北京高明区2017-10-28 05:19:102017-10-28 05:19:10
9991胥杨voluptatem00@example.com黄色17097722096郑州新城区2017-10-28 05:19:102017-10-28 05:19:10
9990凌敏magni22@example.org鲜绿色13021578051杭州涪城区2017-10-28 05:19:102017-10-28 05:19:10
9989席建fugiat_accusantium@example.net18070573726南昌海陵区2017-10-28 05:19:102017-10-28 05:19:10
9988聂新华debitis_sapiente@example.com水色17004061646成都南长区2017-10-28 05:19:102017-10-28 05:19:10

……

原文 https://www.tech1024.cn/original/2960.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值