Laravel how to add new field in query result

蹲街弑〆低调 提交于 2019-12-18 16:52:13

问题


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

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"},
}

回答1:


you can use map()

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


来源:https://stackoverflow.com/questions/44534142/laravel-how-to-add-new-field-in-query-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!