在 Laravel 5 中自动生成存储字符串的语法

问题描述 投票:0回答:1

在 Laravel 5 中的插入中自动生成唯一字符串(MD5(时间戳)或 UUID)的最简单方法是什么。

这就是我现在拥有的。

我的商店功能

public function store(AppointmentsRequest $request)
{
    $appointment = Appointment::create(Request::all());

    return redirect('appointments/'.$appointment->id );
}

我的表架构(请参阅下面的my_ generated_string列)

public function up()
{
    Schema::create('appointments', function(Blueprint $table)
    {
        $table->increments('id');
        $table->integer('client_id')->unsigned();
        $table->foreign('client_id')->references('id')->on('clients')->onDelete('cascade');

        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

        $table->dateTime('appointment_at');

        $table->string('my_generated_string')->unique(); --> Want a generated string in here

        $table->rememberToken();
        $table->timestamps();
    });
}

解决方案注意事项

@JamesFlight 为我的问题提供了一个很好的解决方案。

uniqid() 根据当前时间(以微秒为单位)生成一个字符串(13 个字符长)。由于我的应用程序的两个用户可以(机会很小,但是..)同时创建约会,并且此列在我的数据库中必须是唯一的,因此我在生成的字符串前面添加了 user_id 前缀。由于一个用户不可能在同一微秒内创建两个约会,这应该足以保证我的应用程序的唯一性。

我的功能更改为:

public static function create(array $attributes)
{
    return parent::create(
        array_merge(
            $attributes,
            ['my_generated_string' => uniqid(\Auth::user()->id, true)]
        )
    );
}

注意:

true
将生成 23 个字符的字符串而不是 13 个字符,从而使字符串更加独特。

php laravel
1个回答
0
投票

要么这样做:

public function store()
{
    $appointment = Appointment::create(
        array_merge(
            Request::all(),
            ['my_generated_string' => uniqid()]
        )
    );

    return redirect('appointments/'.$appointment->id );
}

或者重写

Appointment
上的 create 方法:

class Appointment extends Model
{
    public static function create(array $attributes)
    {
        return parent::create(
            array_merge(
                $attributes,
                ['my_generated_string' => uniqid()]
            )
        );
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.