Create a unique field in Codeigniter DBForge Migration

How can I make the financial_year field unique with Codeigniter Dbforge migration?

 function up() { $this->dbforge->add_field(array( 'id' => array( 'type' => 'INT', 'constraint' => 11, 'unsigned' => TRUE, 'auto_increment' => TRUE ), 'financial_year' => array( 'type' => 'VARCHAR', 'constraint' => 20 ), 'start_date' => array( 'type' => 'DATE' ), 'end_date' => array( 'type' => 'DATE' ), 'status' => array( 'type' => "ENUM", 'constraint' => "'Active','Inactive'", 'default' => "Active" ), 'created_on' => array( 'type' => 'TIMESTAMP' ) )); $this->dbforge->add_key('id', TRUE); // add `id` as primary key $this->dbforge->create_table('financial_year'); // create table schema } 
+6
source share
2 answers

There is no way to do this in the database driver.

either write SQL to create the table manually, or (and this is not what I would recommend) modify DB_forge.php and your database driver. (e.g. mysql_forge.php) to have unique keys. looking at the code, I think you will just have a class variable named "unique_keys" and follow the code where the "keys" and "primary keys" should add unique keys.

another option is to use dbforge as written and then just modify the table after creation

 $this->db->query('ALTER TABLE `financial_year` ADD UNIQUE INDEX (`financial_year`)'); 
+8
source

This question is marked as CodeIgniter2 - @ pgee70 Answer is correct

but

CodeIgniter3 supports the creation of unique fields. Just add

 'unique' => TRUE 

in field

In this case:

 'financial_year' => array( 'type' => 'VARCHAR', 'constraint' => 20, 'unique' => TRUE ), 

see CodeIgniter user_guide

+3
source

All Articles