1

when I first made a migration file for table users, the public function down() in the migration file was empty. when I run php spark migrate the table users was created.

then I generated another migration file with php spark make:migration users, made a few adjustments according to the new table structure and put $this->forge->dropTable('users'); in the public function down(). but when I run php spark migrate again, the users table doesn't have the new field..

I'm using codeigniter 4 and mysql. here's my code

UserModelphp

<?php

namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model
{
    protected $DBGroup          = 'default';
    protected $table            = 'users';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $insertID         = 0;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $protectFields    = true;
    // added created_at and updated_at
    protected $allowedFields = ['username', 'password', 'foto', 'nama', 'email', 'telepon', 'created_at', 'updated_at'];

    // Dates
    protected $useTimestamps = false;
    protected $dateFormat    = 'datetime';
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';

    // Validation
    protected $validationRules      = [];
    protected $validationMessages   = [];
    protected $skipValidation       = false;
    protected $cleanValidationRules = true;

    // Callbacks
    protected $allowCallbacks = true;
    protected $beforeInsert   = [];
    protected $afterInsert    = [];
    protected $beforeUpdate   = [];
    protected $afterUpdate    = [];
    protected $beforeFind     = [];
    protected $afterFind      = [];
    protected $beforeDelete   = [];
    protected $afterDelete    = [];
}

first migration file

<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class Users extends Migration
{
    public function up()
    {
        // tabel users
        $this->forge->addField([
            'id' => [
                'type' => 'INT',
                'constraint' => 7,
                'auto_increment' => true,
            ],
            'username' => [
                'type' => 'VARCHAR',
                'constraint' => 50,
                'null' => false,
            ],
            'password' => [
                'type' => 'VARCHAR',
                'constraint' => 255,
                'null' => false,
            ],
            'profile_pic' => [
                'type' => 'VARCHAR',
                'constraint' => 50,
            ],
            'nama' => [
                'type' => 'VARCHAR',
                'constraint' => 50,
            ],
            'email' => [
                'type' => 'VARCHAR',
                'constraint' => 100,
            ],
            'telepon' => [
                'type' => 'VARCHAR',
                'constraint' => 10,
            ],
        ]);
        $this->forge->addKey('id', true);
        $this->forge->createTable('users');
    }

    public function down()
    {
        // hapus tabel users
    }
}

new migration file

<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class Users extends Migration
{
    public function up()
    {
        // tabel users
        $this->forge->addField([
            'id'       => [
                'type'           => 'INT',
                'constraint'     => 7,
                'auto_increment' => true,
            ],
            'username' => [
                'type'       => 'VARCHAR',
                'constraint' => 50,
                'null'       => false,
            ],
            'password' => [
                'type'       => 'VARCHAR',
                'constraint' => 255,
                'null'       => false,
            ],
            'foto'     => [
                'type'       => 'VARCHAR',
                'constraint' => 50,
            ],
            'nama'     => [
                'type'       => 'VARCHAR',
                'constraint' => 50,
            ],
            'email'    => [
                'type'       => 'VARCHAR',
                'constraint' => 100,
            ],
            'telepon'  => [
                'type'       => 'VARCHAR',
                'constraint' => 10,
            ],
            'created_at DATETIME DEFAULT CURRENT_TIMESTAMP',
            'updated_at DATETIME DEFAULT CURRENT_TIMESTAMP',
        ]);
        $this->forge->addKey('id', true);
        $this->forge->createTable('users');
    }

    public function down()
    {
        // hapus tabel users
        $this->forge->dropTable('users');
    }
}

can someone tell me what I'm doing wrong? any help is appreciated

1 Answer 1

5

Explanation:

The down() method isn't called when you execute php spark migrate.

The down() method is run when you perform a migration rollback process using php spark migrate:rollback.

Solution:

Add the $this->forge->dropTable('users'); line of code at the beginning of the up() method of the "new migration file".

new migration file

// ...
class Users extends Migration
{
    public function up()
    {
        $this->forge->dropTable('users');

         // ...
    }
    // ....
}

The purpose of the down() method is to "reverse" everything performed in the up() method.


Extra Notes:

Considering that in your new migration, you're only renaming an existing table column (profile_pic -> foto) and adding timestamp columns, it would make more sense if you specified a more meaningful "migration name".

In addition, instead of dropping & recreating the existing table, modify the table instead. I.e:

new migration file

A. Command (Create the new migration):

php spark make:migration alter_users_rename_profile_pic_add_timestamps

B. Generated migration.

<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class AlterUsersRenameProfilePicAddTimestamps extends Migration
{
    private $tableName = "users";

    public function up()
    {
        $this->forge->modifyColumn($this->tableName, [

            "profile_pic" => [
                'name' => 'foto',
                'type' => 'VARCHAR',
                'constraint' => 50,
            ]
        ]);

        $this->forge->addColumn($this->tableName, [
            'created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP',
            'updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP',
        ]);

    }

    public function down()
    {
        $this->forge->modifyColumn($this->tableName, [

            "foto" => [
                'name' => 'profile_pic',
                'type' => 'VARCHAR',
                'constraint' => 50,
            ]
        ]);

        $this->forge->dropColumn($this->tableName, ["created_at", "updated_at"]);

    }
}

Sign up to request clarification or add additional context in comments.

3 Comments

thanks so much! I didn't see the Extra Notes part in your answer.. did you add that afterwards? anyway, some people say we should use versioning in migration namespace such as 001_create_tblname or YYYYMMDDHHiiss_create_tblname.. which one would you advise?
@dapidmini You're most welcome. Yes, the "Extra Notes' section was added afterwards. Sorry about that!😉 If I understood you correctly, when you say "migration namespace", do you actually mean the "migration filename"?
yes I meant "migration filename".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.