我试图在Laravel 8中建立一个简单的多到多的关系,但我遇到了一个奇怪的问题。我正在构建相当标准的用户/角色关系,但有一个区别:我在这两个表上的主键是一个UUID,而不是一个整数。
没有任何错误,但是当我将一个角色附加到具有$user->roles()->attach($userRole);
的用户时,保存在role_user
链接表中的数据丢失了user_id
,则role_id
被正确插入。我最初遇到了一个role_id
也没有保存的问题,但是我想出了一个问题,那就是在模型上指定protected $keyType = 'string';
。
我无法理解的是,这是我使用UUID造成的,还是我做了其他根本错误。
用户模型
class User extends Authenticatable
{
use HasFactory, Notifiable;
protected $primaryKey = 'id';
protected $keyType = 'string';
protected $fillable = [
'name',
'email',
'password',
];
protected $hidden = [
'password',
'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
protected static function boot()
{
parent::boot();
self::creating(function ($model) {
$model->id = (string)Str::uuid();
});
}
public function roles()
{
return $this->belongsToMany('App\Models\Role')
->using('App\Models\RoleUser');
}
}
RoleUser模型
class RoleUser extends Pivot
{
use HasFactory;
protected $primaryKey = 'id';
protected $keyType = 'string';
protected static function boot()
{
parent::boot();
self::creating(function ($model) {
$model->id = (string)Str::uuid();
});
}
}
我在DB中得到的结果如下。
用户/角色分配代码
$adminRole = Role::where('name', 'admin')->first();
$userRole = Role::where('name', 'user')->first();
$admin = User::create(['name' => 'Admin User', 'email' => 'admin@myapp.com', 'password' => Hash::make('adminpass')]);
$admin->save();
$user = User::create(['name' => 'User User', 'email' => 'user@myapp.com', 'password' => Hash::make('userpass')]);
$user->save();
$admin->roles()->attach($adminRole);
$user->roles()->attach($userRole);
$user->save();
$admin->save();
我真的迷路了,可能是因为我刚来拉勒维尔。
发布于 2020-10-20 06:02:24
因此,如果其他人遇到上述问题,我找到的解决方案是:
在迁移中构建表时,请确保将uuid设置为主$table->uuid('id')->primary();
所有模型都应按以下方式设置:
protected $primaryKey = 'id';
protected $keyType = 'string';
public $incrementing = false;
以上的组合似乎解决了我的问题。它似乎正在构建用户模型,但没有分配它的UUID (尽管它保存在数据库中)。如果我使用$user = User::where('email', '=', 'user@user.com');
简单地重新加载模型,那么它将非常好地工作,因为模型获取ID。
希望这对未来的其他人有帮助!
https://stackoverflow.com/questions/64436623
复制相似问题