Laravel 如何在查询结果中添加新字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44534142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:08:04  来源:igfitidea点击:

Laravel how to add new field in query result

phpjsonlaravellaravel-5backend

提问by PenAndPapers

How can I add new field in each item, I have used put()but it only add on the last item.

如何在每个项目中添加新字段,我已经使用过,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();

Result:

结果:

{
"0": {"teamName": "A"},
"1": {"teamName": "B"},
"2": {"teamName": "C", "test": ['123', '345']},
}

Expected output:

预期输出:

{
"0": {"teamName": "A", "test": "qwerty"},
"1": {"teamName": "B", "test": "qwerty"},
"2": {"teamName": "C", "test": "qwerty"},
}

回答by Kris Roofe

you can use map()

你可以使用地图()

->map(function ($item) {
  $item['test'] = ['123', '345'];
  return $item;
});