Home > Backend Development > PHP Tutorial > Analysis of data migration and data filling in Laravel

Analysis of data migration and data filling in Laravel

不言
Release: 2023-04-01 06:36:02
Original
1418 people have browsed it

This article mainly introduces you to the relevant information about data migration and data filling in Laravel. It introduces the implementation steps in detail through sample code. It has certain reference learning value for everyone's study or work. It needs Let’s take a look at it together.

Preface

This is a basic tutorial, based on the data migration and data filling in the Laravel document, shared for everyone's reference and study , not much to say below, let’s take a look at the detailed introduction.

Understanding about Laravel database migration

When you first see the migration in the laravel framework, you will think that this migration is to transfer data from a database Migrate to another database, or migrate from one server to another server. I have a learning method called As the name suggests, so the above was my first reaction. However, after learning it, I found that this transfer is not the transfer in my understanding, but I don’t know why it is called transfer, so I went to encyclopedia to check it.

Transfer refers to the impact of acquired knowledge, skills, and even methods and attitudes on learning new knowledge and skills. This influence may be positive or negative. The former is called positive transfer or simply transfer, and the latter is called negative transfer or interference. Migration first enables the learned experience to be generalized and systematized, forming a stable and integrated psychological structure, thereby better regulating human behavior and actively acting on the objective world. Migration is the key to transformation into capabilities. On the one hand, the formation of abilities relies on the mastery of knowledge and skills; on the other hand, it also relies on the continuous generalization and systematization of the mastered knowledge and skills. ——Quoted from 360 Encyclopedia

After reading the above encyclopedia description, I actually understand what database migration is. To sum up, migration refers to some kind of impact, so database migration is through the modification of migration files. The impact on the database is actually the operation of the database.

In other words, there is a file in laravel. This file contains laravel's own built-in "commands" for the database. For example, you can create, modify, and delete libraries, tables, and fields. Through the code in these files, the purpose of controlling the database can be achieved through version control. As for how to operate the database through files, we can see the specific instructions in the document.

migration

Laravel provides a database migration method to manage the database. Imagine a scenario: in a multi-person development In the project, your colleague modified a certain database structure and code. Through git, you can synchronize the code modified by the colleague in real time. However, for the database structure, you can only copy the SQL statement modified by the colleague manually. Execute the following Ensure that the database structure is consistent. Then, the concept of database migration in Laravel is a solution for ensuring a consistent database structure within the team.

migration is very simple to use, just write certain php code and execute it, then Laravel will automatically update the database. Suppose your colleague wants to modify a certain field in the database, then you only need to write PHP code, and then you update the code through git. After performing the migrate operation, your database structure will be synchronized with his. Let's take a look at the specific usage.

migrate

Laravel calls writing PHP code for database changes migration, which can be done through php artisan Make:migration filename to create migration files. Suppose you need to create a new user table, then you can create a migration file by executing php artisan make:migration create_user_table --create=user . The execution command will be created in the database/migrations/ directory. A PHP file with file creation time_filename, then this file is the file we will use to write changes to the database structure. One thing to mention here is that although the name of the created migration file can be arbitrary, for the convenience of management, it is best that the file name can reflect the database operation to be performed. For example, here we want to create a user table, so the file name is create_user_table.

php artisan make:migration filename has two optional parameters

  • --create=tablename indicates that the migration is used Create table.

  • --table=tablename indicates that the migration is used to operate on the table tablename.

The migration file create_user_table we created will contain two methods.

public function up()
{
 Schema::create('user', function (Blueprint $table) {
  $table->increments('id');
  $table->timestamps();
 });
}


public function down()
{
 Schema::dropIfExists('user');
}
Copy after login

These two methods are reciprocal operations. For example, we can write the relevant information of the user table we want to create in the up method, while the down method deletes the user table. In this way, we can perform a rollback operation. When we create the user table and find that a field name is written incorrectly, we can delete the user table through down and then re-establish the user table.

Assume that the user table has three fields: id, username, and email, then you can write

in the up method
public function up()
{
 Schema::create('user', function (Blueprint $table) {
  $table->increments('id')->index()->comment('用户id');
  $table->string('name')->default('')->comment('用户名');
  $table->string('email')->nullable()->comment('用户邮箱');
  $table->timestamps();
 });
}
Copy after login

一般,我们的逻辑会在闭包函数中写。上面的代码,即时不能完全明白,也可以大概猜出以下几点:

  • 我们操作的表是 user 表。

  • user 表中定义了 id 字段,因为调用了 increments 方法,所以 id 为 auto_increment,调用了 index 方法说明给 id 添加了索引,最后 comment 等同于注释。

  • 有了 id 的经验,那么 name 字段也很好理解了,string 方法说明 name 是 varchar/char 类型的,default 定义了 name 字段的默认值。

  • email 字段 调用了 nullable 方法说明运行 email 字段为空。

  • 定义字段结构的时候可以使用链式调用的方式。

Laravel 中的方法是满足你对 sql 语句的所有操作,如果你需要定义一个类型为 text 的字段,那么可以调用 text() 方法,更多的方法说明可以参见文档 Laravel 数据库结构构造器。

我们已经编写好了 user 表的结构,接下来执行 php artisan migrate,Laravel 会根据 create 方法自动为我们创建 user 表。至此,我们已经成功的通过 Larvel 的迁移功能来实现创建表。

Rollback

使用 Laravel 的迁移功能可以有后悔药吃。

执行 php artisan migrate 创建 user 表之后,觉得不行,不要 user 这张表,于是你打算删除这张表。那么这时候我们就要使用刚刚说到的 down 方法了。

public function down()
{
 Schema::dropIfExists('user');
}
Copy after login

这里 Laarvel 已经为我们写好逻辑了,dropIfExists 函数就是用来删除表,我们只需要执行 php artisan migrate :rollback 就可以回滚到执行 php artisan migrate 之前的状态。

重命名表

除了创建表,也可以用迁移记录表的其他任何操作,包括修改表属性,修改字段等等操作。这里再举个例子说明如何用迁移来对表进行重命名。

1、假设有表 user,我们需要对它重命名为 users。首先要执行 php artisan make:migration rename_user_to_users --table user 来创建迁移文件。

2、在 up 方法中写我们要重命名表的逻辑。

public function up()
{
 Schema::table('user', function (Blueprint $table) {
  Schema::rename('user','users');
 });
}
Copy after login

3、为了可以 rollback 可以顺利执行,我们还需要在 down 方法中编写撤销重命名操作的逻辑。

public function up()
{
 Schema::table('user', function (Blueprint $table) {
  //
  Schema::rename('users','user');
 });
}
Copy after login

4、最后执行 php artisan migrate 就就可以完成对 user 表的重命名操作。如果需要回滚,只要执行 php artisan migrate:rollback

你会发现,如果执行一次迁移之后,如果执行第二次迁移是不会重复执行的,这是因为 Laravel 会在数据库中建立一张 migrations 的表来记录哪些已经进行过迁移。

基本的 migration 介绍就到这里,以上的内容可以应对大部分的需求,如果需要更详细的介绍,可能需要阅读 Laravel 那不知所云的文档了。:)

Seeder

Laravel 中除了 migration 之外,还有一个 seeder 的东西,这个东西用于做数据填充。假设项目开发中需要有一些测试数据,那么同样可以通过编写 php 代码来填充测试数据,那么通过 git 同步代码,所有的人都可以拥有一份同样的测试数据。

同样,数据填充在 Laravel 中被称为 Seeder,如果需要对某张表填充数据,需要先建立一个 seeder。通过执行 php artisan make:seeder UserTableSeeder 来生成一个 seeder 类。这里我们希望填充数据的表示 test 表,所以名字为 UserTableSeeder。当然这个名字不是强制性的,只是为了做到见名知意。

创建 UserTableSeeder 之后会在 database/seeders 目录下生成一个 UserTableSeeder 类,这个类只有一个 run 方法。你可以在 run 方法中写插入数据库的代码。假设我们使用 DB facade 来向 test 表插入数据。

class UserTableSeeder extends Seeder
{

 public function run()
 {
  DB::table('users')->insert($insertData);
 }
}
Copy after login

编写完代码之后,执行 php artsian db:seeder --class= UserTableSeeder 来进行数据填充。执行完毕之后查看数据库已经有数据了。

如果我们有多个表要进行数据填充,那么不可能在编写完 php 代码之后,逐个的执行 php artisan db:seeder --class=xxxx 来进行填充。有一个简便的方法。在 DatabaseSeeder 的 run 方法中添加一行 $this->call(UserTableSeeder::class);,然后执行 php artisan db:seeder,那么 Laravel 就会执行 DatabaseSeeder 中的 run 方法,然后逐个执行迁移。

和 migration 不同,如果多次执行 php artisan db:seeder 就会进行多次数据填充。

加入你想一次性插入大量的测试数据 ,那么在 run 方法中使用 DB facade 来逐个插入显然不是一个好的方法。Laravel 中提供了一种模型工厂的方式来创建创建大量的数据。

模型工厂

模型工厂,意味着本质其实是一个工厂模式。那么,在使用模型工厂创建数据需要做两件事情

  • 创建工厂,定义好工厂要返回的数据。

  • 调用工厂获取数据。

Laravel 中通过执行 php artisan make:factory UserFactory --model=User 来为 User Model 创建一个工厂类,该文件会放在 database/factory 目录下。打开该文件可以看到如下代码:

$factory->define(App\User::class, function (Faker $faker) {
 return [
  //
 ];
});
Copy after login

这里, return 的值就是我们第 2 步调用工厂获取到的数据。生成数据的逻辑也只需要写在闭包函数中就可以。这里需要提一下 Faker 这个类。这是一个第三方库,Laravel 集成了这个第三方库。这个库的作用很好玩:**用于生成假数据。**假设 User 表需要插入 100 个用户,那么就需要 100 个 username,那么你就不必自己写逻辑生成大量的 test01,test02 这样子幼稚的假数据,直接使用 Faker 类,会替你生成大量逼真的 username。(我也不知道这个算不算无聊了 :)。。。)。

现在假设 User 表有 id, email, username 三个字段,那么我要生成 100 个用户,首先在工厂类中实现逻辑。

$factory->define(App\Models\User::class, function (Faker $faker) {
 return [
  // 直接调用 faker API 生成假数据,更多 faker 相关查看 文档。
  'username' => $faker->name,
  'email' => $faker->unique()->safeEmail,
 ];
});
Copy after login

现在,我们已经定义好了工厂,现在我们就要在 UserSeeder@run 函数中使用模型工厂来生成测试数据。class UserTableSeeder extends Seeder

{

 public function run()
 {
  factory(App\User::class)->times(10)->make()->each(function($user,$index){
   $user->save();
  });
 }
}
Copy after login

run 函数中这一波行云流水的链式调用在我刚刚开始接触 Laravel 的时候也是一脸黑线,不过习惯之后感觉这代码可读性确实很强

  • factory(App\User::class) 指明返回哪个工厂,参数 App\User::class 就是工厂的唯一标识。这里我们在定义工厂的时候 define 的第一个参数已经指明了。

  • ->times(10) 指明需要工厂模式生成 10 个 User 数据。即会调用 10 次 define 函数的第二个参数。

  • ->make() 把生成的 10 个 User 数据封装成 Laravel 中的集合对象。

  • ->each() 是 Laravel 集合中的函数,each 函数会针对集合中的每个元素进行操作。这里直接把数据保存到数据库。

好了,数据迁移和数据填充的基本操作也就这些了。更多复杂的用法。。。。也不一定能用上。

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

关于Laravel接收前端ajax传来的数据解析

关于laravel 5.4中实现无限级分类的方法

The above is the detailed content of Analysis of data migration and data filling in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template