[英]How can I use UUID in spatie/laravel-permission
I'm using ramsey/uuid
as primary key for all of my project tables. 我将ramsey/uuid
用作所有项目表的主键。 How can I disable auto-increment and allow roles
and permissions
primary key to be fillable? 如何禁用自动增量并允许roles
和permissions
主键可填充? I have managed to do it on other tables but I'm stuck with these two. 我已经设法在其他桌子上做到了,但我仍然坚持使用这两张桌子。
Create a folder in app
called Traits
. 在app
创建一个名为Traits
的文件夹。 In there, create a file Uuids.php
. 在其中创建一个文件Uuids.php
。
Add the following code to Uuids.php
; 将以下代码添加到Uuids.php
;
<?php
namespace YourNamespace;
use Illuminate\Support\Str;
trait Uuids
{
/**
* Boot function from Laravel
*/
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
$model->incrementing = false;
$model->{$model->getKeyName()} = Str::uuid()->toString();
});
}
}
Then in your migration file, you should have something like: 然后,在您的迁移文件中,您应具有以下内容:
$table->uuid('id')->primary();
to replace $table->increments('id');
替换$table->increments('id');
Don't forget to use the Uuids trait like so in your models; 不要忘记在模型中使用Uuids特性;
<?php
namespace YourNamespace;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
use Uuids;
protected $guarded = [''];
protected $casts = [
'id' => 'string',
];
...
Before modifying a column, be sure to add the doctrine/dbal
dependency to your composer.json file. 在修改列之前,请确保将doctrine/dbal
依赖项添加到composer.json文件中。 The Doctrine DBAL library is used to determine the current state of the column and create the SQL queries needed to make the specified adjustments to the column: Doctrine DBAL库用于确定列的当前状态,并创建对列进行指定调整所需的SQL查询:
composer require doctrine/dbal
Next you create a migration file; 接下来,创建一个迁移文件。
php artisan make:migration change_primary_key_type_in_roles_table --table=roles
then in your migration file. php artisan make:migration change_primary_key_type_in_roles_table --table=roles
然后在您的迁移文件中。 You do this, eg. 您这样做,例如。
public function up()
{
Schema::table('roles', function (Blueprint $table) {
$table->uuid('id')->change();
});
}
public function down()
{
Schema::table('roles', function (Blueprint $table) {
$table->increments('id')->change();
});
}
Don't forget to do composer dumpautoload
. 不要忘记做composer dumpautoload
。
Hope this helps. 希望这可以帮助。
UPDATE: I wrote a blog post on how to achieve this here 更新:我写了一篇博客文章关于如何在这里实现
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.