Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to seed database in yii2?

I am new to Yii framework. I want to seed my database like it can be done in Laravel framework using Faker. I tried this http://www.yiiframework.com/forum/index.php/topic/59655-how-to-seed-yii2-database/ but it does not provide much details. I would really appreciate if someone can help me out with the steps in details.

like image 263
Faisal Qureshi Avatar asked Jan 25 '16 15:01

Faisal Qureshi


People also ask

What is migration in yii2?

Migration is the base class for representing a database migration. Migration is designed to be used together with the "yii migrate" command. Each child class of Migration represents an individual database migration which is identified by the child class name.


2 Answers

See at fixtures and faker realization in yii2-app-advanced tests. In project you also can write in console php yii fixture/load to load seeds in database and php yii fixture/generate-all to generate seed by faker.

yii.php should have right fixture controller in controllerMap array:

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

See more info in documentation.

like image 82
Onedev_Link Avatar answered Sep 21 '22 17:09

Onedev_Link


Creating console command and using Faker inside the console command controller to seed the database worked for me.
Following is the SeedController.php file which I created under commands folder:

// 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();
            }
        }

    }
}

And used yii seed command to run the controller.

like image 43
Faisal Qureshi Avatar answered Sep 18 '22 17:09

Faisal Qureshi