【发布时间】:2017-05-09 10:55:03
【问题描述】:
那么问题来了:
我创建了一个 CRUD 系统,以便管理员可以创建/读取/更新/删除用户。 问题是我无法在我的 CRUD 系统中为用户选择角色。任何帮助将不胜感激!
我将指出我正在使用的 3 个迁移:用户、角色和他们的数据透视表 user_role。
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('email')->unique();
$table->string('username')->unique();
$table->string('password');
});
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('name', 40);
$table->string('description', 255);
});
Schema::create('user_role', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->integer('user_id');
$table->integer('role_id');
});
这是在我的用户模型中:
public function roles(){
return $this->belongsToMany('App\Role', 'user_role', 'user_id', 'role_id');
}
这是我的榜样:
public function users(){
return $this->belongsToMany('App\User', 'user_role', 'role_id', 'user_id');
}
我像这样在 RoleTableSeeder 中播种一些角色:
Role::create([
'id' => 1,
'name' => 'Admin',
'description' => 'Admin User.'
]);
Role::create([
'id' => 2,
'name' => 'Vendor',
'description' => 'Vendor User.'
]);
Role::create([
'id' => 3,
'name' => 'User',
'description' => 'Simple User.'
]);
这是创建用户的代码:
{!! Form::open(['route' => 'admin.users.allusers']) !!}
<div class="form-group">
{!! Form::label('Username', 'Username:') !!}
{!! Form::text('username',null,['class'=>'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('E-mail', 'E-mail:') !!}
{!! Form::text('email',null,['class'=>'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('Role', 'Role:') !!}
<select class="form-control" id="role" name="role">
<option value="Administrator">Administrator</option>
<option value="Vendor">Vendor</option>
<option value="User" selected="selected">User</option>
</select>
</div>
<div class="form-group">
{!! Form::submit('Create', ['class' => 'btn btn-primary']) !!}
<a href="{{ route('admin.users.allusers')}}" class="btn btn-primary">Back</a>
</div>
{!! Form::close() !!}
【问题讨论】:
-
为什么角色-用户关系是多对多的?您似乎只允许用户在该行中分配一个角色。您可以发布处理表单的控制器代码吗?
-
role_user 是多对多关系,因为我认为可以有很多用户具有相同的角色,反之亦然。
-
public function store(Request $request){ $user=Request::all(); User::create($user); return redirect()->back(); }
标签: php mysql laravel laravel-5 eloquent