Jorge Ribeiro Junior
Jorge Ribeiro Junior

Reputation: 111

Forge Migrate CodeIgniter 4 Foreign Key Error

When using or migrating Codeigniter to generate the relationship in the code below appears or error

Migrate Product

public function up()
{

    $this->forge->addField([
        'id'            => [
            'type'           => 'INT',
            'unsigned'       => TRUE,
            'auto_increment' => TRUE
        ],
        'categories_id' => [
            'type'          => 'INT'
        ],
        'product'       => [
            'type'          => 'VARCHAR',
            'constraint'    => '255'
        ]
    ]);
    $this->forge->addKey('id', TRUE);
    $this->forge->createTable('products');
    $this->forge->addForeignKey('categories_id', 'categories', 'id');

}

Migrate Categories

$this->forge->addField([
        'id'            => [
            'type'           => 'INT',
            'unsigned'       => TRUE,
            'auto_increment' => TRUE
        ],
        'category'      => [
            'type'          => 'VARCHAR',
            'constraint'    => '255'
        ],
        'ordination'    => [
            'type'          => 'INTEGER'
        ],
        'isactive'      => [
            'type'          => 'INTEGER',
            'default'       => 1
        ]
    ]);

    $this->forge->addKey('id', TRUE);
    $this->forge->createTable('categories');

Error

Type: CodeIgniter\Database\Exceptions\DatabaseException Message: Field categories_id not found.

Upvotes: 1

Views: 4422

Answers (1)

Dhaval Chheda
Dhaval Chheda

Reputation: 924

Problem with this code is that after calling

$this->forge->createTable('products');

It will reset the query object, so it will lose the reference to the table and will not find that particular field you are looking for. So change the order of your query like this :

$this->forge->addForeignKey('categories_id', 'categories', 'id');
$this->forge->createTable('products');

Upvotes: 1

Related Questions