繁体   English   中英

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

[英]How to define relation in laravel 5.3 eloquent model?

我的数据库架构中有以下表格,

在此处输入图片说明

是数据透视表吗?

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

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

}

问题是,你需要命名表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);
    }
}

它通过数据透视表Permission_Role将多对多关系绑定在一起。 对于每个表,belongsToMany都没有hasOne或hasMany

class Role {
    public function permissions() {
        return $this->belongsToMany(App\Permission::class);
    }
}

class Permission {
    public function role() {
        return $this->belongsToMany(App\Role::class);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM