【问题标题】:How to set up a user - account - role based relationship in eloquent如何在 eloquent 中建立基于用户 - 帐户 - 角色的关系
【发布时间】:2018-08-19 23:20:53
【问题描述】:

我正在开发一个系统,我需要许多用户可以拥有多个帐户,并且每个帐户可以拥有多个角色。

如何在 eloquent 中进行设置。

我目前在用户模型中:

public function accounts() {
    return $this->belongsToMany('App\Models\Account');
}

public function roles() {
    return $this->belongsToMany('App\Models\Account')->withPivot('role');
}

我有一个定义角色的数据透视表 user_account。

我的问题是当我去的时候

$user = User::with('accounts')
                ->with('roles')
                ->where('id', $user['id'])
                ->first();

我的输出是:

{
  "id": 1,
  "name": "John Doe",
  "created_at": "2018-03-11 20:46:46",
  "updated_at": "2018-03-11 20:46:46",
  "accounts": [
    {
      "id": 1,
      "name": "Acme Inc",
      "type": "BUSINESS",
      "created_at": "2018-03-11 20:46:46",
      "updated_at": "2018-03-11 20:46:46",
      "pivot": {
        "user_id": 1,
        "account_id": 1
      }
    },
    {
      "id": 1,
      "name": "Acme Inc",
      "type": "BUSINESS",
      "created_at": "2018-03-11 20:46:46",
      "updated_at": "2018-03-11 20:46:46",
      "pivot": {
        "user_id": 1,
        "account_id": 1
      }
    }
  ],
  "roles": [
    {
      "id": 1,
      "name": "Acme Inc",
      "type": "BUSINESS",
      "created_at": "2018-03-11 20:46:46",
      "updated_at": "2018-03-11 20:46:46",
      "pivot": {
        "user_id": 1,
        "account_id": 1,
        "role": "SYSTEMADMINISTRATOR"
      }
    },
    {
      "id": 1,
      "name": "Acme Inc",
      "type": "BUSINESS",
      "created_at": "2018-03-11 20:46:46",
      "updated_at": "2018-03-11 20:46:46",
      "pivot": {
        "user_id": 1,
        "account_id": 1,
        "role": "USER"
      }
    }
  ]
}

我想要的是角色只包含来自数据透视表的数据,其中包含 user_id、account_id 和角色名称。任何指针?我还希望帐户输出仅包含一个帐户。

【问题讨论】:

    标签: php eloquent


    【解决方案1】:

    通过在网上广泛搜索,我实际上找到了解决方案。

    您需要创建一个 AccountUser 模型并将角色添加到 account_user 表中。

    在 User 类中你设置了这些关系:

    public function roles() {
        return $this->hasMany('\App\Models\AccountUser');
    }
    
    public function accounts() {
        return $this->hasManyThrough('\App\Models\Account', '\App\Models\AccountUser', 'id', 'id');
    }
    

    在 AccountUser 类中

    public function user() {
        return $this->belongsTo('App\Models\User');
    }
    
    public function account() {
        return $this->belongsTo('App\Models\Account');
    }
    

    在 Account 类中

    public function accountUser() {
        return $this->hasMany('\App\Models\AccountUser');
    }
    

    现在我可以了

    $user = User::with('roles')
                    ->with('accounts')
                    ->where('email', $data['email'])
                    ->first();
    

    我得到了我的预期输出:)

    希望这对某人有所帮助...

    【讨论】:

      猜你喜欢
      • 2015-11-24
      • 2018-06-28
      • 2017-02-09
      • 1970-01-01
      • 1970-01-01
      • 2021-05-04
      • 1970-01-01
      • 2017-03-17
      • 2020-12-10
      相关资源
      最近更新 更多