如何在yii2中播种数据库?

时间:2016-01-25 15:19:52

标签: yii yii2 yii-extensions seeding faker

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

3 个答案:

答案 0 :(得分: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();
            }
        }

    }
}

使用yii seed命令运行控制器。

答案 1 :(得分:5)

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

yii.php应该在fixture数组中拥有正确的controllerMap控制器:

[
    'controllerMap' => [
        'fixture' => [
            'class' => 'yii\console\controllers\FixtureController',
            'namespace' => 'common\ActiveRecords'
        ]
    ]
]

See more info in documentation

答案 2 :(得分:0)

如果您不想进行任何验证,也可以使用batch insert,只需将数组传递给自定义控制台命令即可。

<?php
namespace app\commands;
use Yii;
use yii\console\Controller;
use yii\console\ExitCode;
use yii\db\Command;

class SeedController extends Controller
{
    
       

   
    public function actionUsers()
    {
        Yii::$app->db->createCommand()->batchInsert('users',
        [ 
            'username',
            'password',            
            'createdAt' ,
            'updatedAt'
            ],
            [

               ['user1', 'yourhashedpass', new \yii\db\Expression('NOW()'),new \yii\db\Expression('NOW()')],
['user2', 'yourhashedpass', new \yii\db\Expression('NOW()'),new \yii\db\Expression('NOW()')],
 
                
        ])->execute();
 return ExitCode::OK;

    }
}

运行它

php yii seed/users