如何雄辩地建立基于用户-帐户-角色的关系



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

我怎样才能在雄辩中设置它。

我目前在用户模型中有:

public function accounts() {
    return $this->belongsToMany('AppModelsAccount');
}
public function roles() {
    return $this->belongsToMany('AppModelsAccount')->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和角色名称。有什么指示吗?我还希望帐户输出仅包含一个帐户。

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

您需要创建帐户用户模型并将角色添加到account_user表中。

在 User 类中,设置以下关系:

public function roles() {
    return $this->hasMany('AppModelsAccountUser');
}
public function accounts() {
    return $this->hasManyThrough('AppModelsAccount', 'AppModelsAccountUser', 'id', 'id');
}

在帐户用户类中

public function user() {
    return $this->belongsTo('AppModelsUser');
}
public function account() {
    return $this->belongsTo('AppModelsAccount');
}

并在帐户类中

public function accountUser() {
    return $this->hasMany('AppModelsAccountUser');
}

现在我可以做

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

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

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

最新更新