这是因为当执行迁移时,Laravel会在命令数组的最开始隐式放置任何添加新列或修改现有列的命令。以下代码直接取自Illuminate\Database\Schema\Blueprint
类。
public function toSql(Connection $connection, Grammar $grammar)
{
$this->addImpliedCommands();
$statements = array();
foreach ($this->commands as $command)
{
$method = 'compile'.ucfirst($command->name);
if (method_exists($grammar, $method))
{
if ( ! is_null($sql = $grammar->$method($this, $command, $connection)))
{
$statements = array_merge($statements, (array) $sql);
}
}
}
return $statements;
}
protected function addImpliedCommands()
{
if (count($this->getAddedColumns()) > 0 && ! $this->creating())
{
array_unshift($this->commands, $this->createCommand('add'));
}
if (count($this->getChangedColumns()) > 0 && ! $this->creating())
{
array_unshift($this->commands, $this->createCommand('change'));
}
$this->addFluentIndexes();
}
如上面的代码所示,在
toSql
方法中,会调用
addImpliedCommands
方法,在其中可能会向该对象的命令数组开头添加几个命令。这将导致重命名命令之前先执行新的
mycol
列的命令。
为了解决这个问题,您
不需要创建两个迁移。在同一个迁移中,您可以简单地调用
Schema::table()
两次,如下所示:
Schema::table('mytable', function(Blueprint $table)
{
$table->renameColumn('mycol', 'old_mycol');
});
Schema::table('mytable', function(Blueprint $table)
{
$table->string('mycol', 100);
});