Detailed steps _php instances for data migration and data population in Laravel

Source: Internet
Author: User
Tags define function
This article mainly introduces you to the LaravelData migration and data population, this paper gives you a detailed description of the implementation LaravelData migration and data population, you LaravelInterested in can take a look at Oh!

Objective

This is a basic tutorial, Laravel document data migration and data filling, share out for everyone to reference the study, the following words do not say, come together to see the detailed introduction.

Understanding of Laravel Database Migration

When you first see the migration in the Laravel framework, you will assume that the migration is moving data from one database to another or from one server to another. I learn that I have a learning method called the name, so said is my first reaction, but learned later found that this migration is not my understanding of the migration, but do not know why is called migration, so go to the encyclopedia to check a bit.

Migration refers to the knowledge, skills, and even methods and attitudes that have been acquired to influence the learning of new knowledge and new skills. This effect may be positive or negative, the former being a positive migration or simply a migration, which is called negative migration or interference. Migration first is to make the experience of acquisition generalization and systematization, to form a stable and integrated psychological structure, so as to better regulate human behavior, and actively acting in the objective world. Migration is the key to capacity transformation. The formation of ability depends on the mastery of knowledge and skills, on the other hand, it relies on the continuous generalization and systematization of the knowledge and skills mastered. --cited in 36,000 subjects

Read the above the encyclopedia, in fact, understand what is called a database migration, summed up, migration refers to some kind of impact, so the database migration is through the modification of the migration file to the database impact, this effect is actually operating database.

In other words, there is a file in the Laravel that writes the "command" of the database built into the laravel itself, such as the ability to create modifications to delete libraries, tables, and fields. Through the code in these files, you can control the database through version control, as for how to manipulate the database through the file, we can see the specific instructions in the document.

Migration

Laravel provides a way to manage databases in a database migration scenario: In a multi-person development project, your colleague modifies a database structure and modifies the code, and with Git you can instantly synchronize your colleague's modified code, but the database structure, You can only copy your colleague's modified SQL statements manually, and execute them to ensure that the database is structurally consistent. The concept of database migration in Laravel, then, is the solution to ensure that the database structure is consistent in the team.

Migration is very simple to use, write certain PHP code and execute, then Laravel will update the database automatically. Suppose your colleague wants to modify a field in a database, so long as you write PHP code, then you update the code through GIT, after performing the migrate operation, your database structure is synchronized with him. Let's take a look at the specifics of how to use them.

Migrate

Laravel the PHP code that writes the database changes is called the migration, you can php artisan make:migration filename create the migration file in a way. Assuming you need to create a new user table, you can create a migration file by executing it, and the php artisan make:migration create_user_table --create=user execute command creates a PHP file with the file creation time _filename in the database/migrations/directory. So this is the file we're going to use to write the changes to the database structure. Here to mention, although the name of the creation of the migration file can be arbitrary, but for management convenience, the best 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 called Create_user_table.

PHP artisan make:migration filename has two optional parameters

    • --create=tablename indicates that the migration was used to create the table.

    • --table=tablename indicates that the migration is used to manipulate the TableName table.

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::d ropifexists (' user ');}


These two methods are reciprocal operations, such as we can write information about the user table we want to create in the up method, and the down method is the operation to delete the user table. In this way, we can do the rollback operation, when we create the user table and find that a field name is wrong, we can delete the user table by down, and then re-establish the user table.

Assuming that the user table has id,username,email three fields, you can write in the up method again


Public function up () {schema::create (' user ', function (Blueprint $table) {  $table->increments (' id ')->index ( )->comment (' User ID ');  $table->string (' name ')->default (')->comment (' username ');  $table->string (' email ')->nullable ()->comment (' User email ');  $table->timestamps (); });}


In general, our logic is written in the closure function. The above code, immediately not fully understand, you can probably guess the following points:

    • The table we are manipulating is the user table.

    • The ID field is defined in the user table because the increments method is called, so the ID is auto_increment, the index method description is called, the ID is indexed, and the last comment is the same as the comment.

    • With the experience of ID, the name field is well understood, and the string method shows that name is of type Varchar/char, and default defines the value of the Name field.

    • The email field calls the Nullable method description to run the email field empty.

    • You can use chained calls when defining a field structure.

The method in Laravel is to satisfy all your actions on the SQL statement, and if you need to define a field of type text, you can call the text () method, and more instructions can be found in the document Laravel database structure constructor.

We have written the structure of the user table, and next php artisan migrate , Laravel will automatically create a user table for us based on the Create method. At this point, we have successfully implemented the CREATE table through the Larvel migration feature.

Rollback

Use Laravel's migration function can have regret medicine to eat.

After executing the php artisan migrate user table, I don't think it is possible to do so, so you are going to delete the table. Then we'll use the down method we just talked about.


Public function down () {Schema::d ropifexists (' user ');}


Here Laarvel has written the logic for us, the dropifexists function is used to delete the table, we just need to execute php artisan migrate :rollback can roll back to php artisan migrate the state before execution.

Renaming a table

In addition to creating tables, you can also use any other action that migrates the record table, including modifying table properties, modifying fields, and so on. Here's another example of how to rename a table with a migration.

1, fake with the table user, we need to rename it to users. The first thing to do is to php artisan make:migration rename_user_to_users --table user create the migration file.

2. Write the logic in the up method that we want to rename the table.


Public function up () {schema::table (' user ', function (Blueprint $table) {  schema::rename (' user ', ' users ');});


3, in order to be able to rollback smooth execution, we also need to write in the down method to undo the renaming Operation Logic.


Public function up () {schema::table (' user ', function (Blueprint $table) {  //  schema::rename (' Users ', ' user ');});


4, the last execution will php artisan migrate be able to complete the user table rename operation. If you need to roll back, just execute php artisan migrate:rollback .

You will find that if you perform a second migration after a migration, it is not repeated because Laravel will create a migrations table in the database to record which migrations have been made.

The basic migration Introduction is here, the above content can deal with most of the needs, if need more detailed introduction, may need to read Laravel that unintelligible document. :)

Seeder

Laravel In addition to migration, there is a seeder thing, this thing to do data filling. Assuming that there is some test data in the project development, you can also write PHP code to populate the test data, then the GIT synchronization code, all people can have a copy of the same test data.

Similarly, data fills are called Seeder in Laravel, and if you need to populate a table with data, you need to first create a seeder. Generate a Seeder class by executing PHP artisan make:seeder usertableseeder. Here we want to populate the data representation of the test table, so the name is Usertableseeder. Of course, this name is not mandatory, just to achieve the name of the understanding.

After creating the Usertableseeder, a Usertableseeder class is generated under the Database/seeders directory, which has only one run method. You can write code to insert the database in the Run method. Suppose we use DB facade to insert data into the test table.


Class Usertableseeder extends seeder{public Function run () {  db::table (' users ')->insert ($insertData);}}


After the code is written, it php artsian db:seeder --class= UserTableSeeder is executed to populate the data. After execution, see that the database already has data.

If we have multiple tables to populate the data, it is not possible to populate them one after the PHP code has been written php artisan db:seeder --class=xxxx . There is an easy way. When you add a row to the Databaseseeder Run method $this->call(UserTableSeeder::class); and then execute it php artisan db:seeder , Laravel executes the Run method in Databaseseeder and then executes the migration one by one.

Unlike migration, multiple data fills are performed multiple times php artisan db:seeder .

Join you want to insert a large amount of test data at once, it is obviously not a good way to use the DB facade in the Run method to insert one at a time. Laravel provides a model factory way to create large amounts of data.

Model Factory

The model factory means that the essence is actually a factory model. So, there are two things you need to do to create data using a model factory

    • Create a factory that defines the data that the factory will return.

    • Call the factory to fetch the data.

The Laravel is executed php artisan make:factory UserFactory --model=User to create a factory class for the User Model, which is placed under the Database/factory directory. Open the file to see the following code:


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


Here, the return value is the data that we get from the 2nd step call to the factory. The logic to generate the data is also just written in the closure function. Here you need to mention the Faker class. This is a third-party library that Laravel integrates with this third-party library. The role of this library is fun: * * used to generate false data. * * If the user table needs to insert 100 users, then you need 100 username, then you do not have to write logic to generate a large number of test01,test02 such childish false data, directly using Faker class, will generate a lot of realistic username for you. (I don't know if it's boring:) ... )。

Now suppose the user table has ID, email, username three fields, then I want to build 100 users, first in the factory class to implement the logic.


$factory->define (App\models\user::class, function (Faker $faker) {return [  /////Direct Call Faker API generates false data, more Faker related view text File.  ' username ' = $faker->name,  ' e-mail ' = ' $faker->unique ()->safeemail,];});


Now that we've defined the factory, we're going to use the Model factory in the Userseeder@run function to generate the test data.


Class Usertableseeder extends seeder{public Function run () {  Factory (App\user::class)->times (Ten)->make ()- >each (function ($user, $index) {   $user->save ();  });}}


In the run function, this wave-flowing chain call was a black line when I first started touching Laravel, but I felt the code was very readable after I got used to it.

    • factory(App\User::class)Indicates which factory is returned, and the parameter App\user::class is the factory's unique identity. Here we define the factory at the time the first parameter of define has been indicated.

    • ->times (10) indicates that a Factory mode is required to generate 10 User data. The second parameter of the Define function is called 10 times.

    • ->make () encapsulates the generated 10 User data as a collection object in Laravel.

    • ->each () is a function in the Laravel collection, and each function operates on each element in the collection. This saves the data directly to the database.

Well, that's the basic operation of data migration and data population. More complex usage .... It doesn't have to be used.

Summarize

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.