【问题标题】:How to change some value in Laravel collection output如何更改 Laravel 集合输出中的某些值
【发布时间】:2019-10-05 19:55:03
【问题描述】:

我有一个小型 Laravel 项目致力于收藏编辑。我有口才如下。

public function Import(){
    $org = LabGroup::get();
    return $org;
}

返回结果如下,

[
{
id: 1,
uuid: "491cd440-79d0-11e9-a294-b93a2fd40038",
branch: 0,
name: "productA",
},
{
id: 2,
uuid: "491d0b70-79d0-11e9-aba8-4d9cdb66858f",
branch: 0,
name: "productB",
},
{
id: 3,
uuid: "491d0c20-79d0-11e9-a243-0d208e55c95a",
branch: 0,
name: "productC",
}
]

我需要将所有分支值从 0 更改为 1。我可以循环执行,但我可能会使用其他更好的方法,例如我不熟悉的 'map'。任何建议或指导将不胜感激,谢谢。

【问题讨论】:

    标签: laravel


    【解决方案1】:

    你可以这样使用map()

    $org = LabGroup::get();
    
    $org_branch_1 = $org->map(function ($item, $key) {
        return [
            'id' => $item->id,
            'uuid' => $item->uuid,
            'branch' => 1,
            'name' => $item->name,
        ];
    });
    
    return $org_branch_1;
    

    如果您不需要原始集合,您可以使用相同的方式使用transform()

    $org = LabGroup::get();
    
    return $org->transform(function ($item, $key) {
        return [
            'id' => $item->id,
            'uuid' => $item->uuid,
            'branch' => 1,
            'name' => $item->name,
        ];
    });
    

    编辑:
    这也可以:

    return LabGroup::get()->transform(function ($item, $key) {
                    $item->branch = 1;
                    return $item;
                });
    

    【讨论】:

    • 亲爱的 porloscerros Ψ, 这正是我想要的,无论是映射还是变换。效果很好,非常感谢。
    【解决方案2】:

    您可以在查询中使用 eloquent update() 方法:

    $updatedOrg = LabGroup::get()->update(['branch' => 1]);
    return $updatedOrg; \\Returns the result with the updated branch value.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多