繁体   English   中英

如何将随机字符串列添加到 Laravel 迁移

[英]How to add a random string column to laravel migration

我的 Laravel 应用程序中有一个名为“线程”的表,我想向其中添加一个名为 key 的新列,其中包含长度为 5 的随机字符串。我在 CLL 上运行了 php artisan migrate:make add_key_to_threads 以创建迁移文件。 在我生成的迁移文件中,我使用了 up 函数

Schema::table('threads', function($table){
            $table->str_random('key', 5);
        })

添加新列,之后我在 CLL 上运行了 php artisan migrate。 显然,方法 str_random() 不存在(在谷歌搜索时在资源中找到它),因为我不断收到错误“[BadMethodCallException] 方法 str_random 不存在”。 有人可以指导我正确地做到这一点。

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 类型而异,例如: SQL Server 列的默认随机 10 个字符串值

使用 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

据我所知这是可能的。 在迁移中,您需要像这样创建普通的字符串列:

$table->string('key', 5);

然后在创建新模型时,您应该运行:

$model->key = str_random(5);

假设您在创建模型时使用 Eloquent,您可以使用以下语法:

$thread = new Thread();
// below are sample fields you normally save for this thread
$thread->field_1 = 'value1';
$thread->field_2 = 'value2';
// this is the random key you set
$thread->key = str_random(5);
// now you save thread in database
$thread->save();

给你:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddRandomStringKeyToThreadsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('threads', function (Blueprint $table) {
            $table->string('key');
        });

    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('threads', function (Blueprint $table) {
            $table->dropColumn('key');
        });
    }
}

更新

我已经改变了$table->string('key')->default(str_random(5)); 到这个$table->string('key');

然后使这条路线只是为了更新现有的行......这对我有用......也许你需要为你的表修改它。 但至少你会知道如何去做。

Route::get('/update-table', function () {
    $count = DB::table('threads')->count();

    while ($count > 1){
        DB::table('threads')
            ->where('id', '=', $count)
            ->update(['key' => str_random(5)]);
        $count--;
    }

    return 'DB updated';
});

然后你需要为每个新线程创建一个随机字符串。

简单地使用$this在迁移中使用您的随机字符串生成器。 示例:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class Projects extends Migration
{

    public function up()
    {
        Schema::create('example', function (Blueprint $table) {
            $table->bigIncrements('id');
            // use $this to access class function
            $table->string($this->randString(5));
        });

    }

    // just a random string generator
    public function randString($length){
        $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;

    }


}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM