代码之家  ›  专栏  ›  技术社区  ›  story ks

Laravel 5.4多对多关系

  •  2
  • story ks  · 技术社区  · 8 年前

    类角色

    公共函数admin()。{

    班级管理员

    
    
    

    public function Role(){
        return $this->belongsToMany(Role::class,'pjt_role_admin');
    }
    

    和桌子 pjt_role_admin

    1. 表中的管理员ID admins

    2. pjt_roles

    1 回复  |  直到 8 年前
        1
  •  2
  •   rkj    8 年前

    在关系中指定透视表。默认Laravel假设 admin_role Admin Role

    protected $table = 'pjt_roles';
    
    public function Admin(){ // should be admins() for better readability
        return $this->belongsToMany(Admin::class, 'pjt_role_admin');
    }
    

    public function Role(){ // should be roles() for better readability
        return $this->belongsToMany(Role::class, 'pjt_role_admin');
    }
    

    关系的连接表,雄辩的将连接两个相关模型 公约。您可以通过将第二个参数传递给

    获取数据

    $admin = Admin::find(1);
    $roles = $admin->Role; // should change to roles() in relationship for better readability
    

    $admin->Role()->attach($roleId);
    

    细节 https://laravel.com/docs/5.4/eloquent-relationships#many-to-many