如何定义laravel 5.3 eloquent模型中的关系?

时间:2016-10-07 15:59:23

标签: php mysql laravel model laravel-5.3

我的数据库模式中有表,如下所示,

enter image description here

是数据透视表吗?

如何在雄辩的模型中定义关系?

    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');
    }

}

1 个答案:

答案 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表:

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);
    }
}