laravel - Laravel - 用户表,使 id uuid 类型
问题描述
1- 用户表,使 id uuid 类型。
没问题
php artisan migrate:refresh
但是这个错误
php artisan db:seed
错误:(“SQLSTATE [HY000]:一般错误:1364 字段 'id' 没有默认值”)
2-公司还希望随机分发给用户。在 user 表中,uuid 类型将保存在 user_id 列中。
从现在开始谢谢你...
用户模型:
use UsesUuid;
protected $fillable = ['name', 'email', 'password', 'role', 'slug',];
protected $hidden = ['password', 'remember_token',];
protected $casts = ['email_verified_at' => 'datetime',];
public function companies()
{
return $this->hasMany('App\Company', 'user_id', 'id');
}
UsesUuid 特征:
protected static function boot()
{
parent::boot();
static::creating(function ($post) {
$post->{$post->getKeyName()} = (string)Str::uuid();
});
}
public $incrementing = false;
public function getKeyType()
{
return 'string';
}
用户迁移:
Schema::create('users', function (Blueprint $table) {
$table->uuid('id')->primary()->unique();
$table->string('name',100);
$table->string('email',100);
$table->timestamp('email_verified_at')->nullable();
$table->string('password',100);
$table->string('role',20)->nullable();
$table->string('slug',100);
$table->rememberToken();
$table->timestamps();
$table->softDeletes();
});
公司迁移:
Schema::create('companies', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('user_id',36);
$table->string('name', 100);
$table->timestamps();
$table->softDeletes();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
用户工厂:
$name = $faker->name;
return [
'id' => Str::uuid(),
'name' => $name,
'email' => $faker->unique()->safeEmail,
'email_verified_at' => now(),
'password' => Hash::make(123), // password
'remember_token' => Str::random(10),
'role' => 'user',
'slug' => Str::slug($name),
];
公司工厂:
$name = $faker->company;
return [
'user_id' => Str::uuid(),
'name' => $name,
];
数据库播种机:
factory(App\User::class, 5)->create();
factory(App\Company::class, 1500)->create();
解决方案
像这样修改你的特征:
static::creating(function ($post) {
empty($post->{$post->getKeyName()}) && $post->{$post->getKeyName()} = (string)Str::uuid();
});
在您的迁移中,无需使 UUID 唯一,因为它已经是!
$table->uuid('id');
$table->primary('id');
并且工厂必须自己创建主UUID,不要自己添加
我认为通过这些更改,播种机必须成功运行
推荐阅读
- python - 如何修复 RuntimeWarning:协程
- ibm-midrange - DSPUSRPRF UPCHGD 字段
- python - 关于根据Flask_restx的API对象声明位置路由函数的问题
- ethereum - 我们有两种方式来启动一个 web3 实例,我们选择哪一种更好呢?
- python - 如何在 Python 3.8 的 dbf 文件中写入/附加列?
- algorithm - 在锦标赛排序算法中排序八个数字的最少比较时间是多少?(考虑坏情况)
- amazon-web-services - 适用于 USER_PASSWORD_AUTH 流的 AWS Cognito 开发工具包
- amazon-web-services - EC2 最便宜的地区
- api - Shopware 6 使用 API 的产品变体图像上传问题
- javascript - 使用 getStaticPaths 和 getStaticProps 在 nextjs 中使用 Airtable 中的表中的数据进行分页