Reputation: 1523
Here is my query:
User::with([
'roles' => function ($query) {
$query->select('id AS value', 'display_name AS label');
}
])->with([
'followers' => function ($query) {
$query->select('id', 'user_id');
}
])->find($id);
This is what is executed in mysql:
select `id`, `user_id` from `followers` where
`followers`.`followable_id` in (1) and `followers`.`followable_type` = 'user'
In mysql's console it returs results:
+----+---------+
| id | user_id |
+----+---------+
| 4 | 2 |
| 5 | 3 |
+----+---------+
In json response it is empty:
...
"followers": [],
...
If I omit this line
$query->select('id', 'user_id');
then json response contains
...
"followers" => array:2 [▼
0 => array:6 [▼
"id" => 4
"followable_id" => 1
"followable_type" => "user"
"user_id" => 2
]
1 => array:6 [▼
"id" => 5
"followable_id" => 1
"followable_type" => "user"
"user_id" => 3
]
]
...
What I've tried:
What I need: get list of users ids so that response would contain
...
"followers": [2, 3],
...
I know, i can do foreach
after fetching it from database and modify result but why this one does not work?
Upvotes: 0
Views: 447
Reputation: 131
In with()
function query use addSelect
instaead select because when you use select other selection remove
try that hope it's help
Upvotes: 1
Reputation: 327
Into your with
method from your closures, you should return the Query instance.
Also, if the rendered MySQL query doesn't match what you expect so I think that there is an error with your relationships and/or your MySQL query.
Upvotes: 0