我在Laravel 5.2中有一个用户模型和一个角色模型。在我的角色中,我有学生和老师。每个学生都有很多老师,反之亦然。我该如何链接它们?
答案 0 :(得分:1)
首先,您需要创建三个表roles
- users
- role_user
,如下所示:
角色表:
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
});
然后 用户表
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->rememberToken();
$table->timestamps();
});
user_role表
Schema::create('user_role', function (Blueprint $table) {
$table->bigInteger('user_id')->unsigned();
$table->integer('role_id')->unsigned();
$table->foreign('user_id')
->references('id')->on('users');
$table->foreign('role_id')
->references('id')->on('roles');
});
创建角色模型:
class Role extends Model
{
protected $table = 'roles';
public $timestamps = false;
public function users() {
return $this->belongsToMany(User::class, 'user_role');
}
}
然后将角色关系添加到用户模型
class User extends Authenticatable {
protected $table = 'users';
public function roles() {
return $this->belongsToMany(Role::class, 'user_role');
}
}
为用户提供角色,
$user = User::findOrFail(1); //lets say for user 1
$user->roles()>attach(Role::where('name', 'Teacher')->first());