Schema::table只是更新你的数据库表,不使用对应的SQL语句。在 SQL 中,没有列类型会自动用随机字符串填充您的表。因此列类型必须是string。
查看 Laravel 5.5 中退出的所有类型 https://laravel.com/docs/5.5/migrations#columns
$table->string('key', 5);
下一个问题是key 是否必须是唯一的,如果是,那么您可以附加 unique() 函数:
$table->string('key', 5)->unique();
如果您在第二步中已经有数据,那么您必须填写所有密钥。
您有两种选择来填充列中的随机数据,使用 PHP (Laravel) 或使用 SQL。使用 SQL,您必须编写一个函数,该函数可以根据您的 SQL Server 类型而有所不同,例如:Default random 10 character string value for SQL Server column
使用 Laravel Eloqent,您不必考虑您拥有什么 SQL Server。
$threads = new Threads();
$threads->key = str_random(5);
$threads->save();
如果您使用了->unique() 函数,如果您的 APP 创建了两次密钥,这可能会引发异常。然后你必须捕获异常并再次尝试。
/* only if you need a unique Key */
$threads = new Threads();
while (true)
{
try
{
$threads->key = str_random(5);
$threads->save();
// We could save now we break out of the loop
break;
}
catch (Exception $e)
{
// Could not save, try it again
}
}
对于您现有的行,您可以按如下方式更改迁移:
public function up()
{
Schema::table('threads', function (Blueprint $table)
{
$table->string('key', 5);
});
$existing_threads = Threads::where('key', '')->get();
foreach($existing_threads as $threads)
{
$threads->key = str_random(5);
$threads->save();
}
}
模型Threads 必须在您进行迁移之前退出