Create Unique field in Codeigniter DBForge Migration

假如想象 提交于 2019-12-30 17:41:26

问题


How can I make the financial_year field as unique using 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
}

回答1:


There is not an option to do that in the database driver.

either write the SQL to create the table manually, or (and this isn't what i would recommend) change the DB_forge.php and your database driver. (eg mysql_forge.php) to have unique keys. looking at the code i guess you would just have a class variable called 'unique_keys' and follow the code where 'keys', and 'primary keys' are to add unique keys in.

another option is to use the dbforge as written, then just modifiy the table after creation

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



回答2:


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

but

CodeIgniter3 supports the creation of unique fields. Just add

'unique'            => TRUE

to the field

In this case:

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

see CodeIgniter user_guide



来源:https://stackoverflow.com/questions/21074347/create-unique-field-in-codeigniter-dbforge-migration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!