ALTER TABLE `tablename' ADD UNIQUE (`column name`)It is possible, in FuelPHP, to run any SQL query against the current database, using the DB class, like this:
DB::query("Your_Arbitrary_SQL_Query_Goes_Here")->execute()Using the query() method above, and some raw SQL, it's possible to add unique constraints directly from the migration. Here is a step-by-step example: 1) Using Oil, we automatically generate the migration for a new table called 'members'. We are going to define just one single field in this table, called 'name':
> oil generate migration members name:varchar[100]Oil will generate the migration file. Opening it with your code editor will reveal this:
<?php namespace Fuel\Migrations; class Create_members { public function up() { \DBUtil::create_table('members', array( 'id' => array('constraint' => 11, 'type' => 'int', 'auto_increment' => true), 'name' => array('constraint' => 100, 'type' => 'varchar'), 'created_at' => array('constraint' => 11, 'type' => 'int'), 'updated_at' => array('constraint' => 11, 'type' => 'int'), ), array('id')); } public function down() { \DBUtil::drop_table('members'); } }Note that Oil automatically added 'id', 'created_at' and 'updated_at' fields for us. 2) Just before the end of the 'up' function, add the following:
\DB::query("ALTER TABLE `members` ADD UNIQUE (`name`)")->execute();
<?php namespace Fuel\Migrations; class Create_members { public function up() { \DBUtil::create_table('members', array( 'id' => array('constraint' => 11, 'type' => 'int', 'auto_increment' => true), 'name' => array('constraint' => 100, 'type' => 'varchar'), 'created_at' => array('constraint' => 11, 'type' => 'int'), 'updated_at' => array('constraint' => 11, 'type' => 'int'), ), array('id')); //Adding UNIQUE constraint to 'name' column \DB::query("ALTER TABLE `members` ADD UNIQUE (`name`)")->execute(); } public function down() { \DBUtil::drop_table('members'); } }
> oil refine migrate:up
It looks like you're new here. If you want to get involved, click one of these buttons!