https://coderwall.com/p/mo1gew/custom-datatype-in-laravel-schema-builder
扩展GRAMMAR和Blueprint类
use Illuminate\Support\Fluent;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Grammars\MySqlGrammar;
/**
* Extended version of MySqlGrammar with
* support of 'set' data type
*/
class ExtendedMySqlGrammar extends MySqlGrammar {
/**
* Create the column definition for an 'set' type.
*
* @param \Illuminate\Support\Fluent $column
* @return string
*/
protected function typeSet(Fluent $column)
{
return "set('".implode("', '", $column->allowed)."')";
}
}
/**
* Extended version of Blueprint with
* support of 'set' data type
*/
class ExtendedBlueprint extends Blueprint {
/**
* Create a new 'set' column on the table.
*
* @param string $column
* @param array $allowed
* @return \Illuminate\Support\Fluent
*/
public function set($column, array $allowed)
{
return $this->addColumn('set', $column, compact('allowed'));
}
}
用自定义的方法替换默认的Grammar和Blueprint类
// register new grammar class
DB::connection()->setSchemaGrammar(new ExtendedMySqlGrammar());
$schema = DB::connection()->getSchemaBuilder();
// replace blueprint
$schema->blueprintResolver(function($table, $callback) {
return new ExtendedBlueprint($table, $callback);
});
将migrate文件中的Schema::create 换成 $schema->create
$schema->create('example_table', function(ExtendedBlueprint $table)
{
$table->increments('id');
$table->text('sentence');
// text source & author
$table->string('author')->nullable();
$table->string('source')->nullable();
// technical data
$table->set('difficulty', range(1, 10)); // use new datatype
$table->boolean('enabled')->default(true);
});