如何在yii2中播种数据库?

lmyy7pcs  于 2022-11-09  发布在  其他
关注(0)|答案(3)|浏览(132)

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

cxfofazt

cxfofazt1#

创建控制台命令并在控制台命令控制器中使用Faker来为数据库播种对我来说很有效。
以下是我在commands文件夹下创建的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命令运行控制器。

iaqfqrcu

iaqfqrcu2#

在yii 2-app-advanced测试中可以看到fixtures和faker的实现。在项目中你也可以在控制台中编写php yii fixture/load来加载数据库中的种子,以及php yii fixture/generate-all来生成faker的种子。
yii.phpcontrollerMap数组中应该有正确的fixture控制器:

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

请参阅文档中的详细信息。

au9on6nz

au9on6nz3#

如果您不想进行任何验证,而只是将数组传递给自定义控制台命令(如),则也可以使用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

相关问题