laravel-uuid UUID 未在保存时填写()

laravel-uuid UUID not filled on save()

正在尝试使用它,但是在保存时没有 UUID 被输入到数据库中。

这是我的设置:

数据库: 名称:uuid char(36) utf8mb4_unicode_ci

use Illuminate\Database\Eloquent\Model;
use Cviebrock\EloquentSluggable\Sluggable;
use Emadadly\LaravelUuid\Uuids;

class Account extends Model
{
   use Uuids;

   protected $fillable = [
      'name', 'tname', 'short', 'uuid'
   ];

   protected $guarded = [
      'id'
   ];

控制器:

public function saveUUID(Account $account){
$example = new Account;

    $example->name = 'test';
    $example->short = 'FIVE';
    $example->industry_id = 1;
    $example->user_id = 1;
    $example->status_id = 36;
    $example->save();

return response()->json(['example' => $example]);
}

uuid 字段留空,$example 的响应不包含 uuid。

我错过了什么或做错了什么?

添加到模态:

protected $fillable = array('*');

protected $guarded = ['id'];

我个人会像下面这样创建一个 UUID 特征。

<?php

use Ramsey\Uuid\Uuid;

trait HasUuid
{

protected static function bootHasUuid()
{
    /**
     * Attach to the 'creating' Model Event to provide a UUID
     * for the `uuid` field
     */
    static::creating(function ($model) {
        $columnName = static::getUuidColumn();

        $model->$columnName = Uuid::uuid4();
    });
}

/* Getters and Setters */


public function getUuidAttribute()
{
    $columnName = static::getUuidColumn();

    return $this->attributes[$columnName];
}

protected static function getUuidColumn()
{
    if (isset(static::$uuidColumn)) {
        return static::$uuidColumn;
    }
    return 'uuid';
}

现在您可以在模型中包含 HasUuid 特征

<?php

class Model {
use HasUuid
//.....
}

仅供参考,如果您的 uuid 字段在您的 class 模型中被称为其他名称,您可以像这样声明该字段 static $uuidColumn = 'user_uuid':

Trait 会处理剩下的事情