laravel-uuid UUID未填写save()

时间:2017-11-12 20:58:08

标签: php laravel-5.4 uuid

尝试使用此功能,但在保存时不会将任何UUID输入数据库。

这是我的设置:

DB: 姓名: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字段保留为null,$ example的响应不包含uuid。

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

2 个答案:

答案 0 :(得分:2)

我个人会像以下一样创建一个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字段在您的类模型中被称为其他字段,您可以像static $uuidColumn = 'user_uuid':那样声明该字段。

Trait将处理其余的

答案 1 :(得分:-1)

添加到模式:

protected $fillable = array('*');

protected $guarded = ['id'];