如何在yii2中播种数据库?
发布时间:2020-12-13 18:05:22 所属栏目:PHP教程 来源:网络整理
导读:我是Yii框架的新手. 我想为我的数据库播种,就像可以使用Faker在Laravel框架中完成一样. 我试过这个 http://www.yiiframework.com/forum/index.php/topic/59655-how-to-seed-yii2-database/,但它没有提供太多细节. 如果有人可以帮我解决细节上的步骤,我将非常
我是Yii框架的新手.
我想为我的数据库播种,就像可以使用Faker在Laravel框架中完成一样. 我试过这个 http://www.yiiframework.com/forum/index.php/topic/59655-how-to-seed-yii2-database/,但它没有提供太多细节. 如果有人可以帮我解决细节上的步骤,我将非常感激.
在控制台命令控制器中创建控制台命令并使用Faker为我工作的数据库播种.
以下是我在命令文件夹下创建的SeedController.php文件: // commands/SeedController.php namespace appcommands; use yiiconsoleController; use appmodelsUsers; use appmodelsProfile; class SeedController extends Controller { public function actionIndex() { $faker = FakerFactory::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命令来运行控制器. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |