【发布时间】: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 和角色名称。任何指针?我还希望帐户输出仅包含一个帐户。
【问题讨论】: