如何 return 透视多对多关系的数据?
How to return pivot data of a many-to-many relationship?
如何 select 为具有 id=2
的用户角色转换数据(col1
和 col2
)?
+------------+
| 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
但它 returns:
[
{
"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"
}
]
您可以使用 pluck()
来实现。
https://laravel.com/docs/5.3/collections#method-pluck
User::find(2)->roles->pluck('pivot');
希望对您有所帮助!
如何 select 为具有 id=2
的用户角色转换数据(col1
和 col2
)?
+------------+
| 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
但它 returns:
[
{
"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"
}
]
您可以使用 pluck()
来实现。
https://laravel.com/docs/5.3/collections#method-pluck
User::find(2)->roles->pluck('pivot');
希望对您有所帮助!