Cause:
A few days ago, the customer asked to build a member question and answer system, so I followed the process. When it came time to call the database data, I felt that a It’s a bit stupid to add this~
Solution process:
After checking the manual and looking at foreign blog cases, I came up with a good method~~~
My usage record has been screenshot:
##Until the latter one displays the time, it means that the seeder is running successfully~The following is the official processSeeder CreationIn the Thinkphp5 project, we can enter the following command on the command line:
php think seed:create UserSeeder
UserSeeder file. After the creation is successful, you can
database/seeds See below the directory:
database|-seeds |-|-UserSeeder.php
<?phpuse think\migration\Seeder;class UserSeeder extends Seeder { /** * Run Method. * * Write your database seeder using this method. * * More information on writing seeders is available here: * http://docs.phinx.org/en/latest/seeding.html */ public function run() { } }
run is given by default Method, now we all know that the seeder file is used to generate simulation data, and the code to generate simulation data can be written in the
run method.
run method, we can fill in any code that can fill the database. Here I will give you some ideas:
Requirements: Give the data table
Users to simulate and generate 100 pieces of data. The table structure is as follows:
Description | |
---|---|
nickname
| nickname|
##email<a href="http://www.php.cn/code/114.html" target="_blank"></a> EMAIL | |
Password |
<?phpuse think\migration\Seeder;class UserSeeder extends Seeder { /** * Run Method. * * Write your database seeder using this method. * * More information on writing seeders is available here: * http://docs.phinx.org/en/latest/seeding.html */ public function run() { $rows = []; for ($i = 0; $i < 100; $i++) { $rows[] = [ 'nickname' => mt_rand(10000, 99999), 'email' => mt_rand(10000, 99999).'@qq.com', 'password' => md5('123456'), ]; } $this->table('users')->insert($rows)->save(); } }
Note: Be sure to call the
save()$this->table('users')->insert($rows)->save();method, otherwise it will not be saved.
First, I generated 100 pieces of data, and then called
Insert the generated data into the Users
table of the database. Is not it simple? ^ - ^.Execute Seeder
php think seed:run
Execute Success tip:
All Done. Took 0.0552s. You can see:
##php think seed:run
The above is the detailed content of Thinkphp5 uses the seeder in composer. For more information, please follow other related articles on the PHP Chinese website!