【问题标题】:How can I define this relationship: User belongsToMany Companies and User hasMany Roles/Company in Laravel?我如何定义这种关系:Laravel 中的 User belongsToMany Companies 和 User hasMany Roles/Company?
【发布时间】:2019-11-25 05:55:09
【问题描述】:

我正在创建一个用户可以登录的网站,选择一个公司,然后在选择后为该公司分配角色。每个公司的这些角色可能不同。

我已经尝试了 hasMany 和多态关系,用于用户、公司和角色的表,但无法正常工作。

//In the Role model:    
public function company()
{
    return $this->morphToMany('App\Comp', 'userroles');
}
public function users()
{
    return $this->morphToMany('App\User', 'userroles');
}

我想要一份所选公司的所有角色/用户列表、每个角色的用户/公司列表等等。

【问题讨论】:

    标签: laravel eloquent relationship


    【解决方案1】:

    使用这个:

    //In the Company model:    
    public function users()
    {
        return $this->hasMany('App\User');
    }
    
    //In the User model:
    public function company()
    {
        return $this->belongsTo('App\Comp');
    }
    public function role()
    {
        return $this->hasOne('App\Comp');
    }
    
    //In the Role model:
    public function users()
    {
        return $this->hasMany('App\User');
    }
    

    然后,您可以简单地访问公司中的用户,例如 {{$company->users}}{{$user->company}}{{$user->role}} 或者可能是 {{$role->users}}

    【讨论】:

    • 谢谢 Subham,但是一个用户可以有很多角色,我不明白为什么这个角色有一个公司,因为一个角色可以被不同公司的许多用户使用。
    • 对不起,这是我的错误。它应该在role() 关系中返回Role 模型。此外,将 hasOne 更改为 hasMany。喜欢hasMany('App\Role')。就是这样,一个用户有很多角色。
    猜你喜欢
    • 2021-03-22
    • 1970-01-01
    • 2018-08-11
    • 2015-05-13
    • 2014-05-08
    • 1970-01-01
    • 2018-01-03
    • 2021-10-07
    • 2022-01-16
    相关资源
    最近更新 更多