Last active
October 12, 2020 10:58
-
-
Save bolechen/ca98c08ba8574d93954bdcc3e9006e3f to your computer and use it in GitHub Desktop.
Laravel Model Use Uuid
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
确实是,英文不好 😂