生成Uuid作为主键

时间:2019-08-09 13:58:01

标签: php laravel uuid

请问我在用户模型中生成uuid作为主键时遇到问题。我总是PHP错误:在第11行的C:/xampp/htdocs/twingle/app/Traits/UsesUuid.php中找不到类“ App / Traits / boot”,尝试了各种方法,但此错误仍然存​​在

用户模型(应用\用户)

-

使用特质

UseUuid(App \ Traits)


<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Traits\UsesUuid;

class User extends Authenticatable
{
    use Notifiable,UsesUuid;

    protected $keyType = 'string';

    public $incrementing = false;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

用户迁移

<?php

namespace App\Traits;
use Ramsey\Uuid\Uuid;


trait UsesUuid
{
  public static function UsesUuid()
    {
        boot::creating(function ($model) {
            $model->setAttribute($model->getKeyName(), Uuid::uuid4());
        });
    }
}

请提供任何帮助,我们将不胜感激。谢谢

2 个答案:

答案 0 :(得分:0)

您的特征代码看起来确实不一致。它应该看起来像这样:

>>> string = '1abc'
>>> string[:1].isdigit()
True

>>> string = ''
>>> string[:1].isdigit()
False

这样,当在模型中使用特征时,它将自动挂接到该模型的namespace App\Traits; use Ramsey\Uuid\Uuid; trait UsesUuid { protected static function boot() { parent::boot(); static::creating(function ($model) { $model->setAttribute($model->getKeyName(), Uuid::uuid4()); }); } } 事件中,并确保将主键生成为creating

答案 1 :(得分:-1)

选择一个模型观察者。更干净,更合身。 https://laravel.com/docs/5.8/eloquent#observers