以下是我的疑问:
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);这就是在mysql中执行的内容:
select `id`, `user_id` from `followers` where
`followers`.`followable_id` in (1) and `followers`.`followable_type` = 'user'在mysql的控制台中,returs的结果是:
+----+---------+
| id | user_id |
+----+---------+
| 4 | 2 |
| 5 | 3 |
+----+---------+在json响应中,它是空的:
...
"followers": [],
...如果我省略了这一行
$query->select('id', 'user_id');然后json响应包含
...
"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
]
]
...我试过的是:
我需要的是:获取用户I列表,以便响应包含
...
"followers": [2, 3],
...我知道,在从数据库中获取并修改结果之后,我可以做foreach,但是为什么这个不能工作呢?
发布于 2017-05-15 10:44:58
在with()函数查询中,使用addSelect instaead select,因为当使用select时,其他选择删除
试着希望这能帮上忙
发布于 2017-05-15 09:56:24
从闭包到with方法,您应该返回查询实例。
另外,如果呈现的MySQL查询与您预期的不匹配,那么我认为您的关系和/或MySQL查询出现了错误。
https://stackoverflow.com/questions/43974382
复制相似问题