function ($query) { $query->select('id AS value'-6ren">
gpt4 book ai didi

php - 如果我尝试选择单列,Laravel 的 "with"方法将返回空列表

转载 作者:行者123 更新时间:2023-11-29 10:49:35 26 4
gpt4 key购买 nike

这是我的查询:

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 的控制台中它返回结果:

+----+---------+
| 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
]
]
...

我尝试过的:

  1. $query->select('id', 'user_id');
  2. $query->select('user_id');
  3. $query->select('id', '*');//这将返回之前显示的内容

我需要什么:获取用户 ID 列表,以便响应包含

...
"followers": [2, 3],
...

我知道,我可以在从数据库中获取它并修改结果后执行 foreach 但为什么这个不起作用?

最佳答案

with()函数查询中使用addSelect代替select,因为当您使用select其他选择时删除

尝试一下希望有帮助

关于php - 如果我尝试选择单列,Laravel 的 "with"方法将返回空列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43974382/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com