如何返回多对多关系的数据透视数据?

时间:2017-02-21 19:09:24

标签: mysql laravel eloquent octobercms laravel-eloquent

如何为col1用户的角色选择数据透视数据(col2id=2)?

+------------+
|    User    |
+------------+
| id | name  |
+----+-------+
| 1  | John  |
+----+-------+
| 2  | Brian |
+----+-------+

+------------+
|    Role    |
+------------+
| id | title |
+----+-------+
| 1  | Admin |
+----+-------+
| 2  | Owner |
+----+-------+

+-----------------------------------+
|              UserRole             |
+-----------------------------------+
| user_id | role_id |  col1 |  col2 |
+---------+---------+-------+-------+
|    2    |    1    | lorem | dolor |
+---------+---------+-------+-------+
|    2    |    2    | ipsum |  amet |
+---------+---------+-------+-------+

我可以使用User::find(2)->roles,但它会返回:

[
  {
    "id": 1,
    "title": "Admin",
    "pivot": {
      "user_id": 2,
      "role_id": 1,
      "col1": "lorem",
      "col2": "dolor"
    }
  },
  {
    "id": 2,
    "name": "Owner",
    "pivot": {
      "user_id": 2,
      "role_id": 2,
      "col1": "ipsum",
      "col2": "amet"
    }
  }
]

如何将查询更改为仅具有以下结果(仅限数据透视数据):

[
  {
    "user_id": 2,
    "role_id": 1,
    "col1": "lorem",
    "col2": "dolor"
  },
  {
    "user_id": 2,
    "role_id": 2,
    "col1": "ipsum",
    "col2": "amet"
  }
]

1 个答案:

答案 0 :(得分:1)

您可以使用pluck()来实现此目标。

https://laravel.com/docs/5.3/collections#method-pluck

User::find(2)->roles->pluck('pivot');

希望这有帮助!