Reputation: 111
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
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