首页 > 解决方案 > 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
    },
    ...


]

标签: phplaraveleloquent

解决方案


你应该试试下面的代码

Maker::select(['maker_name AS label', 'id AS value'])->where('type_id', $request->type_id)->has('maker')->has('listing')->withCount(['listing'])->get();

推荐阅读