php Laravel Uuid Trait

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php Laravel Uuid Trait相关的知识,希望对你有一定的参考价值。

<?php
namespace App\Traits;
use Ramsey\Uuid\Uuid;
use Illuminate\Database\Eloquent\ModelNotFoundException;

trait Uuid
{
    /**
     * Boot function from laravel.
     */
    protected static function bootUuids()
    {
        static::creating(function ($model) {
            if (!$model->{config('uuid.default_uuid_column')}) {
                $model->{config('uuid.default_uuid_column')} = Uuid::uuid4()->toString();
            }
        });
        static::saving(function ($model) {
            $original_uuid = $model->getOriginal(config('uuid.default_uuid_column'));
            if ($original_uuid !== $model->{config('uuid.default_uuid_column')}) {
                $model->{config('uuid.default_uuid_column')} = $original_uuid;
            }
        });
    }
    /**
     * Scope  by uuid 
     * @param  string  uuid of the model.
     * 
    */
    public function scopeUuid($query, $uuid, $first = true)
    {
        $match = preg_match('/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/', $uuid);
        if (!is_string($uuid) || $match !== 1)
        {
            throw (new ModelNotFoundException)->setModel(get_class($this));
        }
    
        $results = $query->where(config('uuid.default_uuid_column'), $uuid);
    
        return $first ? $results->firstOrFail() : $results;
    }
}

以上是关于php Laravel Uuid Trait的主要内容,如果未能解决你的问题,请参考以下文章

php Laravel:HasDatatable Trait

php Laravel:HasDatatable Trait API端点

Laravel trait的使用

PHP 特性之 trait

PHP 特性之 trait

php Laravel与uuid的多态关系