【问题标题】:Laravel how to add new field in query resultLaravel如何在查询结果中添加新字段
【发布时间】: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"},
}

【问题讨论】:

    标签: php json laravel laravel-5 backend


    【解决方案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;
    猜你喜欢
    • 2017-06-24
    • 2021-03-14
    • 2017-09-21
    • 2017-05-30
    • 2021-04-02
    • 2021-10-10
    • 2016-04-04
    • 2019-11-24
    • 2020-09-05
    相关资源
    最近更新 更多