CodeIgniter Forums
How can I remove a unique constraint on a field when performing a down migration? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: How can I remove a unique constraint on a field when performing a down migration? (/showthread.php?tid=78110)



How can I remove a unique constraint on a field when performing a down migration? - SteeveDroz - 12-02-2020

Copy-pasted from https://stackoverflow.com/questions/65039833/how-can-i-remove-a-unique-constraint-on-a-field-when-performing-a-down-migration, feel free to answer the question there too to win a few points.

I have to add a unique constraint to a field after the table was created. I therefore set up a migration file with this in the up() method:
Code:
$fields = [
    'slug' => [
        'type' => 'varchar',
        'constraint' => 255,
        'unique' => true
    ]
];
$this->forge->modifyColumn('pages', $fields);
And in down():
Code:
$fields = [
    'slug' => [
        'type' => 'varchar',
        'constraint' => 255,
        'unique' => false
    ]
];
$this->forge->modifyColumn('pages', $fields);
This doesn't work.

When calling
Code:
php spark migrate:rollback
, the migration is correctly un-applied ("migrations" table is modified) but the fields stay unique.
What should I put in down() instead?


RE: How can I remove a unique constraint on a field when performing a down migration? - InsiteFX - 12-02-2020

I don't think that you can without deleting the field and adding it in again


RE: How can I remove a unique constraint on a field when performing a down migration? - daveontheciforum - 12-12-2020

You could execute some SQL to delete it directly:


PHP Code:
public function down()
{
  
    $this
->db->simpleQuery("ALTER TABLE pages DROP INDEX slug");




(the unique index will have a name - if you don't know what it is, you can get it with this: SHOW INDEX FROM pagesWink