This creates a simple ''guitars'' table in a database.\\

The MySQL code would have been like this
<code>
create table guitars (
 id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
 brand VARCHAR(64) NOT NULL,
 model VARCHAR(64) NOT NULL
);
</code>

First generate a migration file like this
<code>
./yii migrate/create create_guitars_table
</code>

Then edit the migration file created in the ''migrations'' folder.

It will be something like this
<code>
<?php

use yii\db\Migration;

/**
 * Handles the creation of table `guitars`.
 */
class m180625_070240_create_guitars_table extends Migration
{
    /**
     * {@inheritdoc}
     */
    public function safeUp()
    {
        $this->createTable('guitars', [
            'id' => $this->primaryKey(),
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function safeDown()
    {
        $this->dropTable('guitars');
    }
}
</code>

Add
<code>
            'brand' => $this->string(64)->notNull(),
            'model' => $this->string(64)->notNull()
</code>
under the 'id' line.

Then apply the migration with
<code>
./yii migrate
</code>

You can also create the migration in one go with
<code>
./yii migrate/create create_guitars_table --fields="brand:string(64):notNull,model:string(64):notNull"
</code>

**An bigger example to create two tables for employee and company**
<code>
./yii migrate/create create_employee_table --fields="company_id:smallinteger:notNull,emp_name:string(64):notNull,emp_email:string(64),emp_salary:decimal,expiry_date:date,created_at:datetime,modified_at:datetime"

./yii migrate/create create_company_table --fields="name:string(64):notNull,email:string(64),location:string(32):notNull,created_at:datetime,modified_at:datetime"
</code>

In the migration file, you can populate with some dummy data. For the **employee** table, in ''safeUp'' after the ''createTable'' block
<code php>
// insert some employee data
   $columns = ['company_id', 'emp_name', 'emp_email', 'emp_salary', 'expiry_date', 'created_at', 'modified_at'];
   $this->batchInsert('employee', $columns, [
    [1, 'John Smith', 'john@test.com', 45000, '', '2015-04-10','2015-04-10'],
    [2, 'Amy Flecther', 'amy@test.com', 49000, '2018-01-01', '2015-04-11', '2015-04-11'],
    [1, 'John Doe', 'doe@test.com', 52000, '', '2015-04-12', '2015-04-12'],
   ]);
</code>

Similarly you can populate the **company** table by adding the following
<code php>
// insert some company data
    $columns = ['name', 'email', 'location', 'created_at', 'modified_at'];
    $this->batchInsert('company', $columns, [
     ['360Networks Inc.', 'contact@360network.com', 'London', '2015-04-10', '2015-04-10'],
     ['Arkeia Software', 'contact@arkeia.com', 'Birmingham', '2015-04-11', '2015-04-11'],
    ]);
</code>


Back to [[yii|Yii Main Index]]