dongzongxun8491
2018-06-01 14:30
浏览 45
已采纳

Laravel Eloquent - 查询数据透视表

in my Laravel app I have three database tables called users, projects and roles. There is m:n relation between them so I have also pivot table called project_user_role. Pivot table contains user_id, project_id and role_id columns. See image for screenshot from MySQL Workbench.

enter image description here

My User, Project and Role models got defined belongsToMany relation like that:

//User model example
public function projects()
{
    return $this->belongsToMany('App\Library\Models\Project', 'project_user_role')->withPivot(['user_id','role_id']);
}

Now I can easily get projects of authenticated user like that:

$user = Auth::user();
$projects = $user->projects;

Response of this looks like that:

[
  {
      "id": 1,
      "name": "Test project",
      "user_id": 1,
      "created_at": "2018-05-01 01:02:03",
      "updated_at": "2018-05-01 01:02:03",
      "pivot": {
          "user_id": 2,
          "project_id": 17,
          "role_id": 1
      }
  },
]

but I would like to "inject" information about user role into response likat that:

[
  {
      "id": 1,
      "name": "Test project",
      "user_id": 1,
      "created_at": "2018-05-01 01:02:03",
      "updated_at": "2018-05-01 01:02:03",
      "pivot": {
          "user_id": 2,
          "project_id": 17,
          "role_id": 1
      },
      roles: [
        {
            "id": 1,
            "name": "some role name",
            "display_name": "Some role name",
            "description": "Some role name",
            "created_at": "2018-05-01 01:02:03",
            "updated_at": "2018-05-01 01:02:03",
        }
      ]
  },
]

Is it possible? Thanks

图片转代码服务由CSDN问答提供 功能建议

在我的Laravel应用程序中,

我有三个数据库表,称为用户,项目和角色。 它们之间有m:n关系,所以我还有一个名为project_user_role的数据透视表。 数据透视表包含user_id,project_id和role_id列。 请参阅图片,了解MySQL Workbench的截图。</ p>

</ p>

我的用户,项目和角色模型已获得 像这样定义belongsToMany关系:</ p>

  //用户模型示例
公共函数项目()
 {
返回$ this-&gt; belongsToMany('App \ Library \ Models  \ Project','project_user_role') - &gt; withPivot(['user_id','role_id']); 
} 
 </ code> </ pre> 
 
 

现在我可以轻松获得项目 经过身份验证的用户:</ p>

  $ user = Auth :: user(); 
 $ projects = $ user-&gt; projects; 
 </ code> </  pre> 
 
 

响应如下:</ p>

  [
 {
“id”:1,
“name”:“Test  project“,
”user_id“:1,
”created_at“:”2018-05-01 01:02:03“,
”updated_at“:”2018-05-01 01:02:03“,\  n“pivot”:{
“user_id”:2,
“project_id”:17,
“role_id”:1 
}  
},
] 
 </ code> </ pre> 
 
 

但我想将有关用户角色的信息“注入”到响应中:</ p> < pre> [ { “id”:1, “name”:“Test project”, “user_id”:1, “created_at”:“2018-05-01 01: 02:03“, ”updated_at“:”2018-05-01 01:02:03“, ”pivot“:{ ”user_id“:2, ”project_id“:17, ” role_id“:1 }, 角色:[ { ”id“:1, ”名称“:”某个角色名称“, ”display_name“:”某个角色名称“, “description”:“some role name”, “created_at”:“2018-05-01 01:02:03”, “updated_at”:“2018-05-01 01:02:03”, } ] }, ] </ code> </ pre>

有可能吗? 谢谢</ p> </ div>

2条回答 默认 最新

相关推荐 更多相似问题