Laravel如何在查询结果中添加新字段
Posted
技术标签:
【中文标题】Laravel如何在查询结果中添加新字段【英文标题】:Laravel how to add new field in query result 【发布时间】:2017-11-15 23:28:52 【问题描述】:如何在每一项中添加新字段,我使用了put()
,但它只添加到最后一项。
return self::where('latest', 1)
->where('competitionId',$competitionId)
->orderBy('won','desc')
->orderBy('teamName','asc')
->get(['teamName','played','won','lost','percentage', 'streak'])
->put('test', ['123', '345'])
->toJson();
结果:
"0": "teamName": "A",
"1": "teamName": "B",
"2": "teamName": "C", "test": ['123', '345'],
预期输出:
"0": "teamName": "A", "test": "qwerty",
"1": "teamName": "B", "test": "qwerty",
"2": "teamName": "C", "test": "qwerty",
【问题讨论】:
【参考方案1】:你可以使用map()
->map(function ($item)
$item['test'] = ['123', '345'];
return $item;
);
【讨论】:
Collection #389 ▼ #items: array:8 [▼ 0 => null 1 => null 2 => null 3 => null 4 => null 5 => null 6 => null 7 => 空] 所有项目都返回null 我忘记了return $item
;以上是关于Laravel如何在查询结果中添加新字段的主要内容,如果未能解决你的问题,请参考以下文章