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

来源:互联网 发布:网络环境监控 编辑:程序博客网 时间:2024/05/22 20:25

写在前面

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

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

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

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

数据迁移

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

创建迁移文件

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

php artisan make:migration create_students_table

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

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

<?phpuse 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 too 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 too 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

<?phpnamespace App;use Illuminate\Database\Eloquent\Model;/** * 学生模型 */class Student extends Model{}
创建填充文件
php artisan make:seed StudentsTableSeeder

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

<?phpuse 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文件,修改为

<?phpuse 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文件,我们定义一下要填充的数据格式

<?phpuse 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表是否有数据了呢?

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

……

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