Laravel中主鍵使用UUID(注意點)

這裏的UUID採用  webpatser/laravel-uuid 安裝的方法能夠在GitHub上進行查看一步步進行安裝laravel


須要注意的是,在安裝完和配置完後,想要在調用模型的 create方法時讓模型自動生成UUID的主鍵須要在模型中添加如下的配置git

public $incrementing = false;

public static function boot(){
  parent::boot();
  self::creating(function ($model) {
    $model->id = (string) CommonUtils::uuid();
  });
}
紅色區域的方法是我本身封裝的,原先他生成的UUID中帶 - 因此我本身封裝的將它去掉了,另外注意下UUID的長度! 

將上面的方法添加完後,在使用create時就能夠自動生成UUID了!github

記得在使用前須要引入
use Webpatser\Uuid\Uuid;
/**
 *  這一段是GitHub上的原方法!
 */
public static function boot()
{
    parent::boot();
    self::creating(function ($model) {
        $model->uuid = (string) Uuid::generate(4);
    });
}
相關文章
相關標籤/搜索