我的数据库模式中有表,如下所示,
是数据透视表吗?
如何在雄辩的模型中定义关系?
class Role extends Model {
public $timestamps = false;
public function permissions() {
return $this->hasMany('App\Models\RolePermission', 'permissions_id');
}
}
这是定义关系的正确方法吗?请帮我理解。
和
class RolePermission extends Model {
public $timestamps = false;
public function role() {
return $this->belongsTo('App\Models\Role', 'roles_id');
}
}
答案 0 :(得分:0)
问题是您需要为表格permission_role
命名,以遵循设计实用程序。
Schema::create('roles', function(Blueprint $table){
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Schema::create('permissions', function(Blueprint $table){
$table->increments('id');
$table->string('name');
$table->timestamps();
});
然后你只需要permission_role
表:
Schema::create('permission_role', function(Blueprint $table){
$table->increments('id');
$table->integer('permission_id')->unsigned();
$table->foreign('permission_id')->references('id')->on('permissions')->onDelete('cascade');
$table->integer('role_id')->unsigned();
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
});
然后你就像这样设置你的模型:
class Role {
public function permissions() {
return $this->hasMany(App\Permission::class);
}
}
当然是您的许可类
class Permission {
public function role() {
return $this->belongsToMany(App\Role::class);
}
}