laravel uuid 作为主键

Alb*_*rto 4 uuid laravel laravel-events

我正在尝试将 uuid 设置为 Laravel 模型中的主键。我已经在模型中设置了启动方法,如此处所示因此我不必每次想要创建和保存模型时都手动创建它。我有一个控制器,它只创建模型并将其保存在数据库中。

它已正确保存在数据库中,但当控制器返回时,id 的值始终以0. 我怎样才能让它真正返回它在数据库中创建的值?

模型

class UserPersona extends Model
{
    protected $guarded = [];

    protected $casts = [
        'id' => 'string'
    ];

    /**
     *  Setup model event hooks
     */
    public static function boot()
    {
        parent::boot();
        self::creating(function ($model) {
            $uuid = Uuid::uuid4();
            $model->id = $uuid->toString();
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

控制器

class UserPersonaController extends Controller
{
    public function new(Request $request)
    {
        return UserPersona::create();
    }
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*uge 5

您需要将keyTypetostringincrementingto更改为false。因为它没有增加。

public $incrementing = false;
protected $keyType = 'string';
Run Code Online (Sandbox Code Playgroud)

另外,我有一个trait,我只需将其添加到那些具有 UUID 键的模型中。这非常灵活。这最初来自https://garrettstjohn.com/articles/using-uuid-laravel-eloquent-orm/,我对它进行了一些小的调整,以解决我在大量使用它时发现的问题。

use Illuminate\Database\Eloquent\Model;
use Ramsey\Uuid\Uuid;

/**
 * Class Uuid.
 * Manages the usage of creating UUID values for primary keys. Drop into your models as
 * per normal to use this functionality. Works right out of the box.
 * Taken from: http://garrettstjohn.com/entry/using-uuids-laravel-eloquent-orm/
 */
trait UuidForKey
{

    /**
     * The "booting" method of the model.
     */
    public static function bootUuidForKey()
    {
        static::retrieved(function (Model $model) {
            $model->incrementing = false;  // this is used after instance is loaded from DB
        });

        static::creating(function (Model $model) {
            $model->incrementing = false; // this is used for new instances

            if (empty($model->{$model->getKeyName()})) { // if it's not empty, then we want to use a specific id
                $model->{$model->getKeyName()} = (string)Uuid::uuid4();
            }
        });
    }

    public function initializeUuidForKey()
    {
        $this->keyType = 'string';
    }
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。