2

我正在尝试将 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();
        });
    }
}

控制器

class UserPersonaController extends Controller
{
    public function new(Request $request)
    {
        return UserPersona::create();
    }
}
4

1 回答 1

4

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

public $incrementing = false;
protected $keyType = 'string';

此外,我有一个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';
    }
}

希望这可以帮助。

于 2020-04-15T09:12:04.123 回答