How to migrate data and populate data in Laravel?

php中世界最好的语言
Release: 2023-03-18 06:46:01
Original
1491 people have browsed it

I have summarized a tutorial to teach you how to migrate data and fill data in Laravel documents. Without further ado, let’s take a look at the detailed introduction.

When I first saw migration in the laravel framework, I thought that the migration was to move data from one database to another, or from one server to another. 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 impact may be positive or negative. The former is called positive transfer or simply transfer, and the latter is called negative transfer or interference. Transfer is first of all to generalize and systematize the acquired experience and form 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 depends on the mastery of knowledge and skills; on the other hand, it also depends 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 project developed by multiple people, your colleague modified a certain database structure. And the code has been modified. Through git, you can synchronize the code modified by colleagues in real time. However, for the database structure, you can only manually copy the SQL statements modified by colleagues and execute them to 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 the PHP code that changes the database a migration. You can create a migration file through php artisan make:migration filename. 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. Executing the command will create a file creation time_filename in the database/migrations/ directory. php file, 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 The name is create_user_table.

php artisan make:migration filename has two optional parameters

--create=tablename indicating that the migration is used to create a 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 in the down method The operation of deleting 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.

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

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

in the up method


Generally, our logic will be written in the closure function. Even if you don't fully understand the above code, you can roughly guess the following points:

The table we operate is the user table.

The id field is defined in the user table. Because the increments method is called, the id is auto_increment. The index method is called to add an index to the id. Finally, comment is equivalent to a comment.

With the experience of id, the name field is also easy to understand. The string method explains that name is of varchar/char type, and default defines the default value of the name field.

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中文网其它相关文章!

相关阅读:

实例详解ajax实现无刷新上传文件功能

PHP中使用jQuery+Ajax实现分页查询功能

AJAX实现简单的注册页面异步请求实例代码

The above is the detailed content of How to migrate data and populate data 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