How I can add column before another column in dbforge?

2.8k Views Asked by At

I want to add column that name 'accept_loc', type 'VARCHAR' to 3 database tables (use dbforge library from codeigniter) Assum they are named t1,t2,t3.

t1 structure:

  • id
  • bla_bla
  • pick_up_loc
  • ....

t2 structure:

  • id
  • pick_up_loc
  • ....

t3 structure:

  • id
  • bla_bla
  • pick_up_loc
  • ....

if I used this code below in my migration up function:

$fields = array(
        'accept_lat' => array(
            'accept_loc' => 'VARCHAR',
            'constraint' => '50',
            'after' => 'id',
        ),
    );
$this->dbforge->add_column('t1',$fields);
$this->dbforge->add_column('t2',$fields);
$this->dbforge->add_column('t3',$fields);

result:

t1 structure:

  • id
  • accept_loc
  • bla_bla
  • pick_up_loc
  • ....

t2 structure:

  • id
  • accept_loc
  • pick_up_loc
  • ....

t3 structure:

  • id
  • accept_loc
  • bla_bla
  • pick_up_loc
  • ....

it's not a good looking structure. How can I add column before 'pick_up_loc' to all of them (n database tables).

3

There are 3 best solutions below

0
On

Please try to put the after in uppercase, that is 'AFTER', there was a bug in that after key and mentioned got fixed here.

    $fields = array(
        'accept_lat' => array(
            'accept_loc' => 'VARCHAR',
            'constraint' => '50',
            'AFTER' => 'id'
        )
    );
0
On

The third argument in add_column() is $after_field. So you can't add the column before another column but you can do this:

$this->dbforge->add_column('t1', $fields, 'bla_bla');
$this->dbforge->add_column('t2', $fields, 'id');
$this->dbforge->add_column('t3', $fields, 'bla_bla');

Also, you seem to be naming the field 'accept_lat' and then using 'accept_loc' instead of the 'type' element which is confusing things.

0
On

Late to the party but to clarify your code, on t1 for example, should look like this:

 $fields = array(
            'accept_lat' => array('type' => 'TEXT')
);
    $this->dbforge->add_column('t1', $fields, 'id');

So accept_lat will be added after the id column in table t1.