Skip to content

Instantly share code, notes, and snippets.

@bolechen
Last active October 12, 2020 10:58
Show Gist options
  • Save bolechen/ca98c08ba8574d93954bdcc3e9006e3f to your computer and use it in GitHub Desktop.
Save bolechen/ca98c08ba8574d93954bdcc3e9006e3f to your computer and use it in GitHub Desktop.
Laravel Model Use Uuid
<?php
namespace App\Traits;
use Illuminate\Support\Str;
trait HasUuid
{
/**
* Get the route key for the model.
*
* @return string
*/
public function getRouteKeyName()
{
return 'uuid';
}
public static function findByUuidOrFail($uuid)
{
return self::whereUuid($uuid)->firstOrFail();
}
/**
* Eloquent scope to look for a given UUID.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $uuid The UUID to search for
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeWithUuid($query, $uuid)
{
return $query->where('uuid', $uuid);
}
/**
* Eloquent scope to look for multiple given UUIDs.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param array $uuids The UUIDs to search for
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeWithUuids($query, array $uuids)
{
return $query->whereIn('uuid', $uuids);
}
protected static function bootHasUuid()
{
static::creating(function ($model) {
if (!$model->uuid) {
// 这里使用了 orderedUuid 方便后期分表
$model->uuid = (string) Str::orderedUuid();
}
});
}
}
@bolechen
Copy link
Author

这个 Trait 名改成 HasUuid 可能会更贴合模型语义化。

确实是,英文不好 😂

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment