How to return pivot data of a many-to-many relationship?
Ad
How can I select pivot data (col1
and col2
) for roles of user with id=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 |
+---------+---------+-------+-------+
I can use User::find(2)->roles
but it 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"
}
}
]
How can I change the query to only have the following result (only pivot data):
[
{
"user_id": 2,
"role_id": 1,
"col1": "lorem",
"col2": "dolor"
},
{
"user_id": 2,
"role_id": 2,
"col1": "ipsum",
"col2": "amet"
}
]
Ad
Answer
Ad
You can use pluck()
to achieve this.
https://laravel.com/docs/5.3/collections#method-pluck
User::find(2)->roles->pluck('pivot');
Hope this helps!
Ad
source: stackoverflow.com
Related Questions
Ad
- → I can't do a foreign key, constraint error
- → How to implement DbDongle::convertTimestamps as workaround of invalid timestamps with MySql strict
- → MySQL error "Foreign key constraint is incorrectly formed"
- → Eloquent Multitable query
- → "Laravel 5.1" add user and project with userId
- → Database backup with custom code in laravel 5 and get the data upto 10 rows from per table in database
- → Laravel 5.1 QueryException when trying to delete a project
- → Using Array in '->where()' for Laravel Query Building
- → Chaining "Count of Columns" of a Method to Single Query Builder
- → Laravel Eloquent Joining Strange query
- → convert time using mysql laravel 5
- → How to update a column after an expiration date in MySQL?
- → Foreign key constraint fails on existing key
Ad