PhpLaravel framework Learning (I): creating a database and filling in Test Data

Source: Internet
Author: User
PhpLaravel framework Learning (1) Laravel of phpLaravel framework learning: creating a database and filling in test data. Before establishing a database, we have already defined the basic functions of the target website. Now we will first establish a database. From the functional perspective of the database design, our database only needs two tables. The admin table is used to store the Administrator account information.

Php Laravel framework Learning (1) php Laravel framework learning Laravel database creation and filling test data before establishing a database we have already defined the basic functions of the target website. Now let's first establish its database. From the functional perspective of the database design, our database only needs two tables. The admin table is used to store the Administrator account information.

Php Laravel framework Learning (1)

Php Laravel framework learning: Laravel establishes a database and fills in Test Data

Create a database

We have already clarified the basic functions of the target website. Now we will first establish its database.

Design Database

In terms of functions, our database only needs two tables. The admin table is used to store the Administrator account information, while the docs table is the document data. Of course, you can decide the names of the two tables by yourself.

We have built a simple documentation website, so the database can be very simple. In the admin table, we only need the id, email, and password fields. In the docs table, we create five fields: id, title, content, create_date, and last_change.

Next, we can create these two tables. The simplest method is to create them directly in mysql. You can use the visual phpmyadmin tool or the mysql command line. But here we will talk about using the laravel framework to create it.

Framework settings

First, we need to set the laravel framework to open the application/config/application. php file. We need to set the key parameter in the file to any 32-Bit String:

'key' => 'YourSecretKeyGoesHere!',
 
 

This string is used to encrypt our password. Then, set the database information in application/config/database. php. The database is created in advance and you can name it at will:

'mysql' => array(        'driver'   => 'mysql',        'host'     => 'localhost',        'database' => 'database',        'username' => 'root',        'password' => '123456',        'charset'  => 'utf8',        'prefix'   => '',        ),
 
 
  1. Create a database

Then we will use Artisan and Migrations tools to create a database. You can simply think of it as a database tool, and we need to initialize it before using it. First, add your php Directory to the system's environment variables, and then open the cmd Tool cd to the web root directory to run the command:

php artisan migrate:install
 
 

This is a table named laravel_migrations added to the database. It records the data required by migrate. Then run the following two commands:

php artisan migrate:make create_admin_tablephp artisan migrate:make create_docs_table
 
 

After running successfully, we can see two files named date _ creat_admin_table.php and date _ creat_docs_table.php in the application/migrations directory.

Open the creat_admin_table.php file and add the code in the up and down methods:

 
 
  1. public function up(){    Schema::create('admin',function($table)    {        $table->increments('id');        $table->string('email',64);        $table->string('password',64);     });     DB::table('admin')->insert(array(                        'email'=>'your email',                        'password'=>Hash::make('your password'),                    ));}public function down(){    Schema::drop('admin');}

Edit the creat_docs_table.php file:

 
 
  1. public function up(){    Schema::create('docs',function($table)    {        $table->increments('id');        $table->string('title',64);        $table->text('content');        $table->string('create_date',12);        $table->string('last_change',12);    });     DB::table('docs')->insert(array(                        'title'=>'test',                        'content'=>'just a test!',                        'create_date'=>time(),                        'last_change'=>''                    ));}public function down(){    Schema::drop('docs');}

After saving the file, run the following command:

 
 
  1. php artisan migrate
  2. // If you see the following two prompts, the database has been created. Migrate: application/2012_08_14_043216_create_admin_tableMigrate: application/2012_08_14_043242_create_docs_table

Very good. The website database has been built, and we have inserted two pieces of data for testing.

Database filling and migration

In the previous sections, we talked about data migration. data migration can create a data table structure. In fact, data migration can also insert data. You need to create a new migration file:

1 php artisan migrate:make seed_authors_table  

Run the following command:

Edit the newly generated file 2014_03_12_063755_seed_authors_table.php,

 1 
 insert(15             array(16                 array(17                     'name' => 'Bowen',18                     'age' => 25,19                     'active'=> 1,20                     'email'=>'bowen@nova.com',21                     'bio' => '',22                     'role_id'  => 223                 ),24                 array(25                     'name' => 'Judith',26                     'age' => 21,27                     'active'=>0,28                     'email'=>'judith@nova.com',29                     'bio' => '',30                     'role_id'  => 131                 )32             ));33     }34 35     /**36      * Reverse the migrations.37      *38      * @return void39      */40     public function down()41     {42         DB::table('authors')->delete();43     }44 }

Run the migration file as follows:

View the Database "authors" table and find two more data points:

Disadvantages of database migration padding

Although we can use the database migration method for filling, this method has many disadvantages:

  • If the migration rollback is performed, the added data will be lost;
  • It is troublesome to change data
Laravel database filling (Seeder)

From 4, artisan now provides a clever way to populate the database. Migration should never be applied to the filling database. Data filling uses the artisan db: seed command to easily complete the filling operation.

This simple method fills your database with test data through the fill class. All filling classes are stored in the app/database/seeds directory. The filling class can be named in the form, but it is best to follow some reasonable constraints, such as UserTableSeeder. By default, a DatabaseSeeder class is defined for you. In this class, you can use the call function to run other filling classes, allowing you to control the filling sequence.

Create a new filling File

To fill the "authors" table with data, create the new file AuthorTableSeeder. php In the app/database/seeds directory and edit the file:

 1 
  'Test1', 8                     'age' => 25, 9                     'active'=> 1,10                     'email'=>'test1@nova.com',11                     'bio' => '',12                     'role_id'  => 213         ));14     }15 }

Then execute the artisan command line:

1 php artisan db:seed --class=AuthorTableSeeder

Then a new record is added to the database.

Another global execution method is php artisan db: seed, which can execute multiple filling classes. This method is the executed DatabaseSeeder class. We edit this class:

1 class DatabaseSeeder extends Seeder {2 3/** 4 * Run the database seeds. 5*6 * @ return void 7 */8 public function run () 9 {10 Eloquent: unguard (); 11 12 $ this-> call ('authortablesecret '); // call the 'authortablesecret' Filling Class 13 14 $ this-> command-> info ('employee table seeded! '); 15} 16 17}

You can also use the migrate: refresh command to fill the database. The database will be rolled back and re-run all the migration tasks. Then, execute php artisan db: seed, and the data will be added successfully.

1 php artisan migrate:refresh --seed


Laravel framework Official Website: http://v4.golaravel.com/docs/4.2

Http://yancjie.blog.163.com/blog/static/2009290172012811113459690/

Http://www.cnblogs.com/huangbx/p/Laravel_6.html

Getting started with the framework:

Http://www.uncletoo.com/html/application/773.html

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.