如何在yii2中播种数据库?

Fai*_*shi 7 yii seeding faker yii-extensions yii2

我是Yii框架的新手.我想为我的数据库播种,就像可以使用Faker在Laravel框架中完成一样.我试过这个http://www.yiiframework.com/forum/index.php/topic/59655-how-to-seed-yii2-database/,但它没有提供太多细节.如果有人可以帮助我完成细节步骤,我将非常感激.

Fai*_*shi 11

在控制台命令控制器中创建控制台命令并使用Faker来为我工作的数据库播种.
以下是SeedController.php我在命令文件夹下创建的文件:

// commands/SeedController.php
namespace app\commands;

use yii\console\Controller;
use app\models\Users;
use app\models\Profile;

class SeedController extends Controller
{
    public function actionIndex()
    {
        $faker = \Faker\Factory::create();

        $user = new Users();
        $profile = new Profile();
        for ( $i = 1; $i <= 20; $i++ )
        {
            $user->setIsNewRecord(true);
            $user->user_id = null;

            $user->username = $faker->username;
            $user->password = '123456';
            if ( $user->save() )
            {
                $profile->setIsNewRecord(true);
                $profile->user_id = null;

                $profile->user_id = $user->user_id;
                $profile->email = $faker->email;
                $profile->first_name = $faker->firstName;
                $profile->last_name = $faker->lastName;
                $profile->save();
            }
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

并使用yii seed命令来运行控制器.


One*_*ink 6

在yii2-app-advanced测试中查看fixtures和faker实现.在项目中,您还可以在控制台中编写以php yii fixture/load在数据库中加载种子php yii fixture/generate-all并由faker生成种子.

yii.php应该fixturecontrollerMap数组中有正确的控制器:

[
    'controllerMap' => [
        'fixture' => [
            'class' => 'yii\console\controllers\FixtureController',
            'namespace' => 'common\ActiveRecords'
        ]
    ]
]
Run Code Online (Sandbox Code Playgroud)

查看文档中的更多信息.