我可以使用Ramsey Uuid缩短此方法吗?

时间:2016-01-27 17:38:20

标签: php oop laravel-5 uuid

这是我当前的创建方法;

public function create(Request $request)
{
    // 1. create a uuid string
    $uuid1 = Uuid::uuid1();
    $uuid = $uuid1->toString();

    // 2. check if it already exists in the database
    $response = Response::where('uuid', $uuid)->first();

    // 3. if it does, run this method again and get a new uuid
    if ($response) {
        return $this->create($request);
    }

    // 4. create an array with a uuid key and put the value in it
    $data['uuid'] = $uuid;

    // 5. create the record in the database
    $response = Response::create($data);

    // 6. look up the record I have just created to return in order to return the group
    $response = Response::where('uuid', $response->uuid)->first();

    // 7. redirect passing the uuid and the group
    return redirect()->route('survey', ['uuid' => $response->uuid, 'group' => $response->group]);
}

部分内容似乎有些过分。有没有办法安全地解决这个问题?特别是,第6步。有没有办法将它与5结合起来并立即引用我创建的记录?

另外,有没有办法可以删除第2步和第3步,并确信Uuid永远不会重复?我知道机会非常小但仍然存在。

1 个答案:

答案 0 :(得分:0)

获取相同的UUID几乎是不可能的,因此您可以安全地删除步骤2和3.但是,如果要检查数据库中的UUID,可以使用do-while-loop代替步骤1,2和3: / p>

do {
    $uuid = (string) Uuid::uuid1();
} while ($response = Response::where('uuid', $uuid)->first());

接下来,您不必运行步骤6. Request::create将返回一个Eloquent Request对象,以便您可以在步骤7中使用它。$response->group应该通过延迟加载来获取。