我有以下型号:
<?php
// namespaces removed for brevity
class User extends Model {
/** {@inheritdoc} */
protected $fillable = [
'email',
'password',
'last_name',
'first_name',
'permissions',
];
/** {@inheritdoc} */
protected $hidden = ['password'];
/**
* @var string serve pra armazenar o nome da tabela desta entidade
*/
protected $table = 'users';
/**
* @var bool deve criar campos para salvar datas da última alteração
*/
public $timestamps = false;
/**
*
*/
public function addRole(Role $role): void
{
$this->roles->put($role); // works in runtime but not persistence
$this->roles->add($role); // can't remember what happens
$this->roles()->attach($role); // User not persisted yet, so with no ID cannot construct relation
}
/**
* Creates relationship with roles table.
*/
public function roles(): BelongsToMany
{
// return $this->belongsToMany(Permission::class)->using(RolePermission::class);
$pivotName = (new UserRole())->getTable();
return $this->belongsToMany(Role::class, $pivotName)->withTimestamps();
}
}
这些是我要执行的步骤:
new User
。User::addRole(Role $role)
向其添加角色(请参见方法代码和注释)。User::save()
保留用户实例。用户存储在数据库中,而不是角色关系。