php - Laravel Eloquent Query 使用 withCount 和 get([name as value])
问题描述
当我尝试使用 withCount 检索记录同时想要将字段返回为不同的名称时,我在 laravel 中遇到问题。如果我删除 getCount,查询将正确返回字段,但是当我添加 withCount 时,它将忽略语句中的 AS 子句。
Maker::where('type_id', $request->type_id)->get(['maker_name AS label', 'id AS value']);
正确返回带有道具“标签”和“值”的对象数组
Maker::where('type_id', $request->type_id)->has('maker')->has('listing')->withCount(['listing'])->get(['maker_name AS label', 'id AS value']);
此语句忽略 AS 子句,只返回数据库中添加了 listing_count 字段的记录
我想要的是返回的查询:
[
{
label : 'string',
value : int,
listing_count : int
},
...
]
解决方案
你应该试试下面的代码
Maker::select(['maker_name AS label', 'id AS value'])->where('type_id', $request->type_id)->has('maker')->has('listing')->withCount(['listing'])->get();
推荐阅读
- python - Flask FileField 显示完整路径
- json.net - 使用 NewtonSoft 从 JSON 模式创建参考 JSON 数据
- bash - Git Difftool p4merge Diff上的意外提示
- r - 为 2 个条形创建一个包含 3 个轨迹的堆积条形图
- laravel - 提交前的 Laravel Mix
- excel-formula - AND / OR 公式在数据验证工具中无法正常工作
- javascript - 尝试从 Android 上的网络应用推送通知
- mysql - 如何在 Larave 8 中保存具有多个外键的记录?
- sqlite - 在 CentOS 7 上编译 sqlite3-devel 3.35.4
- expression - 如何根据 SSRS 中的独特患者创建一个计算条件数量的表达式?