Laravel Realizes Database Migration and Supports Chinese Filling

  • 2021-08-10 07:30:50
  • OfStack

Preface

Database migration is actually versioning the structural changes of database tables, The previous way of modifying the database table structure is relatively primitive, For example, a new field is added to a library table, They are all directly modified by executing alter table xxx add in the library table. But there are some drawbacks to doing so. For example, in the development phase, if your own library table is modified, you have to pass this sql statement to others and execute it again. This is not a good way when many people work together. Is there a way for us to do some simple version control on the modification of database library table, and at the same time, let others synchronize our database modifications conveniently?

The answer is that we can use Migrations built into Laravel.

What are the parts of database management?

In fact, Laravel's version management of database mainly includes two departments: the management of database structure and the management of data.

Database structure management: Mainly to manage the database structure, such as adding a table, a table added a field and so on. Data management: This is mainly to manage the data in the table, generate 1 some filling data, and solve the problem that there is no test data when we develop and debug.

Often we do projects in teams, and everyone is in their own local database. If you have ever had colleagues manually add fields to the database structure, database migration can solve your problem.

Not only that, when deploying online, it also avoids the trouble of manually importing the database or manually modifying the data structure. Data migration helps you maintain the data structure conveniently.

Data filling, so that we need a lot of false data when testing, we can easily fill a lot of data in batches instead of creating data one by one.

This article is based on Laravel 5.5, and other versions are similar.

Data migration

If we need a student table, we will no longer use the native SQl statement to create the table.

Create a migration file

The premise is that the database connection information has been configured


php artisan make:migration create_students_table

This command generates a file like 2017_10_28_035802_create_students_table. php in the database/migrations/ directory

We add the data structure of the students table inside


<?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 Is the name of the table 
 Schema::create('students', function (Blueprint $table) {
  //  Storage engine 
  $table->engine = 'InnoDB';
  // id Self-increasing 
  $table->increments('id');
  //  Student name 
  $table->string('name');
  //  Gender 
  $table->string('sex');
  //  Mailbox 
  $table->string('email');
  //  Favorite color 
  $table->string('favorite_color');
  //  Mobile phone number 
  $table->string('phone');
  //  Address 
  $table->string('addr');
  //  Automatic maintenance timestamp 
  $table->timestamps();
 });
 }

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

For more usage, please refer to the official manual.

Running migration


php artisan migrate

This will run all the migration files in the database/migrations/ directory and automatically create the migrations table to record the migration files that have already been run and prevent duplicate runs.

Let's see if the database has automatically created students table.

If the following error occurs:


[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

In the database/migrations/ directory, there will be two migration files for laravel's own user and password reset, which will run simultaneously.
Here we solve this problem by modifying the character set under mysql in the database configuration file config/database. php to utf8


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

If you want to know why, you can poke: https://www.ofstack.com/article/127319. htm

Data Filling (Supports Chinese)

Create a student table Eloquent model

Create Student. php in the app directory


<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

/**
 *  Student model 
 */
class Student extends Model
{
 
}

Create a fill file


php artisan make:seed StudentsTableSeeder

This command generates the StudentsTableSeeder. php fill file in the database/seeds/directory


<?php

use Illuminate\Database\Seeder;

class StudentsTableSeeder extends Seeder
{
 /**
 * Run the database seeds.
 *
 * @return void
 */
 public function run()
 {
 //  Call model factory   Generate 10000 Bar data 
 factory(App\Student::class, 10000)->create();
 }
}

Call the Seeders

We open the database/seeds/DatabaseSeeder. php file and modify it to


<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
 /**
 * Run the database seeds.
 *
 * @return void
 */
 public function run()
 {
 //  Call the student table to fill the file 
 $this->call(StudentsTableSeeder::class);
 }
}

Create Model Factory Populations


php artisan make:factory StudentsFactory -m Student

This command generates the StudentsFactory. php file in the database/factories/directory. We define the data format to be populated under 1


<?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 Is the name of the table 
 Schema::create('students', function (Blueprint $table) {
  //  Storage engine 
  $table->engine = 'InnoDB';
  // id Self-increasing 
  $table->increments('id');
  //  Student name 
  $table->string('name');
  //  Gender 
  $table->string('sex');
  //  Mailbox 
  $table->string('email');
  //  Favorite color 
  $table->string('favorite_color');
  //  Mobile phone number 
  $table->string('phone');
  //  Address 
  $table->string('addr');
  //  Automatic maintenance timestamp 
  $table->timestamps();
 });
 }

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

See vendor/fzaninotto/faker/src/Faker/Generator. php for more configuration

Let faker fill in Chinese


<?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 Is the name of the table 
 Schema::create('students', function (Blueprint $table) {
  //  Storage engine 
  $table->engine = 'InnoDB';
  // id Self-increasing 
  $table->increments('id');
  //  Student name 
  $table->string('name');
  //  Gender 
  $table->string('sex');
  //  Mailbox 
  $table->string('email');
  //  Favorite color 
  $table->string('favorite_color');
  //  Mobile phone number 
  $table->string('phone');
  //  Address 
  $table->string('addr');
  //  Automatic maintenance timestamp 
  $table->timestamps();
 });
 }

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

Start filling

First, let's perform 1:


<?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 Is the name of the table 
 Schema::create('students', function (Blueprint $table) {
  //  Storage engine 
  $table->engine = 'InnoDB';
  // id Self-increasing 
  $table->increments('id');
  //  Student name 
  $table->string('name');
  //  Gender 
  $table->string('sex');
  //  Mailbox 
  $table->string('email');
  //  Favorite color 
  $table->string('favorite_color');
  //  Mobile phone number 
  $table->string('phone');
  //  Address 
  $table->string('addr');
  //  Automatic maintenance timestamp 
  $table->timestamps();
 });
 }

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

Automatically load the fill file we created under 1 in the database/seeds/directory to avoid the following errors:


[ReflectionException]
Class StudentsTableSeeder does not exist

Then we run the fill command:


<?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 Is the name of the table 
 Schema::create('students', function (Blueprint $table) {
  //  Storage engine 
  $table->engine = 'InnoDB';
  // id Self-increasing 
  $table->increments('id');
  //  Student name 
  $table->string('name');
  //  Gender 
  $table->string('sex');
  //  Mailbox 
  $table->string('email');
  //  Favorite color 
  $table->string('favorite_color');
  //  Mobile phone number 
  $table->string('phone');
  //  Address 
  $table->string('addr');
  //  Automatic maintenance timestamp 
  $table->timestamps();
 });
 }

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

Since we are filling in 10,000 pieces of data, it can take a little longer to refresh the database and look at the data added one by one.

Be crowned with success

If there is no error in the above operations, look at whether there is data in our database table 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

...

Summarize


Related articles: