


Detailed steps for data migration and data filling in Laravel_php example
This article mainly introduces you to the relevant information about data migration and data filling in Laravel. The article introduces in detail the implementation of data migration and data filling in Laravel through sample code. For the steps of data filling, if you are interested in Laravel, you can take a look!
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 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 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 structure of the database 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 The 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'); }
These two methods are reciprocal operations. For example, we can write the user table we want to create in the up method. Related information, and the down method is 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.
假设 user 表有 id,username,email 三个字段,那么可以再 up 方法中写
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(); }); }
一般,我们的逻辑会在闭包函数中写。上面的代码,即时不能完全明白,也可以大概猜出以下几点:
我们操作的表是 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'); }
这里 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'); }); }
3、为了可以 rollback 可以顺利执行,我们还需要在 down 方法中编写撤销重命名操作的逻辑。
public function up() { Schema::table('user', function (Blueprint $table) { // Schema::rename('users','user'); }); }
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); } }
编写完代码之后,执行 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 [ // ]; });
这里, 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, ]; });
现在,我们已经定义好了工厂,现在我们就要在 UserSeeder@run 函数中使用模型工厂来生成测试数据。
class UserTableSeeder extends Seeder { public function run() { factory(App\User::class)->times(10)->make()->each(function($user,$index){ $user->save(); }); } }
run 函数中这一波行云流水的链式调用在我刚刚开始接触 Laravel 的时候也是一脸黑线,不过习惯之后感觉这代码可读性确实很强
factory(App\User::class)
指明返回哪个工厂,参数 App\User::class 就是工厂的唯一标识。这里我们在定义工厂的时候 define 的第一个参数已经指明了。->times(10) 指明需要工厂模式生成 10 个 User 数据。即会调用 10 次 define 函数的第二个参数。
->make() 把生成的 10 个 User 数据封装成 Laravel 中的集合对象。
->each() 是 Laravel 集合中的函数,each 函数会针对集合中的每个元素进行操作。这里直接把数据保存到数据库。
好了,数据迁移和数据填充的基本操作也就这些了。更多复杂的用法。。。。也不一定能用上。
总结
以上就是本篇文章的所有内容了,希望可以对大家带来帮助,对Laravel感兴趣的同学和可以在本站搜索相关视频教程进行学习!
相关推荐:
The above is the detailed content of Detailed steps for data migration and data filling in Laravel_php example. For more information, please follow other related articles on the PHP Chinese website!

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Dreamweaver Mac version
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6
Visual web development tools