【问题标题】:Laravel change collection attributes nameLaravel 更改集合属性名称
【发布时间】:2018-11-25 12:24:07
【问题描述】:

您将如何更改集合的属性?
所以返回的是属性改变的模型集合,而不是数组集合。

问题是,我想做一些翻译演示者,所以当我得到集合时,我可以 dd($collection) 而不是'name',它会显示'nome',也使用 response()- >json($collection) 将显示更改后的名称。

类似 $presenterNames = ['name' => 'nome', 'id' => 'identificador'];并且不在此处的名称将正常调用。

Collection {#213 ▼
    #items: array:2 [▼
        0 => Category {#215 ▼
            +timestamps: false
            #fillable: array:2 [▶]
            #connection: "mysql"
            #table: "categories"
            #primaryKey: "id"
            #keyType: "int"
            +incrementing: true
            #with: []
            #withCount: []
            #perPage: 15
            +exists: true
            +wasRecentlyCreated: false
            #attributes: array:3 [▼
            "id" => 1
            "name" => "categoria1"
            "slug" => "categoria1"
            ]
            #original: array:3 [▶]
            #changes: []
            #casts: []
            #dates: []
            #dateFormat: null
            #appends: []
            #dispatchesEvents: []
            #observables: []
            #relations: []
            #touches: []
            #hidden: []
            #visible: []
            #guarded: array:1 [▶]
            #slugOptions: null
        }
        1 => Category {#219 ▶}
    ]
}

所以基本上我想改变

#attributes: array:3 [▼
    "id" => 1
    "name" => "categoria1"
    "slug" => "categoria1"
]

到这里

#attributes: array:3 [▼
    "identificador" => 1
    "nome" => "categoria1"
    "slug" => "categoria1"
]

使用关联数组进行动态处理。

【问题讨论】:

  • 为什么要改变这个,为什么不从 db 改变?
  • 因为我想使用英文约定维护数据库,但我希望能够在需要时翻译密钥,使用分形真的很容易,但分形仅适用于数组或 json响应,但如果该响应不是数组或 json,我想仍然使用该集合。

标签: laravel laravel-5.7 laravel-collection


【解决方案1】:

解决方案:

在您的模型中添加以下代码。

  protected $appends = ['nome'];

  public function getNomeAttribute(){

    return $this->attributes['name'];

 }

你可以通过查询$modelObj->nome来访问它;

对所有需要的属性执行相同操作。

这也将反映在您的 JSON 响应中。

谢谢

参考:https://laravel.com/docs/5.7/eloquent-mutators#defining-an-accessor

【讨论】:

  • 这不会影响性能吗?而不是在制作集合之前直接更改,迭代更改每个听起来有点沉重,这会返回一个数组而不是集合返回,所以在映射它之后我不能真正使用集合方法或任何其他方法,所以我也无法调用 $something->relationship->something
  • 能否指定输入类型和返回类型。您可以修改上面的代码,使其使用 toArray() 返回数组。
  • 基本上我只是想改变集合属性,所以 return 仍然是一个集合,类似于 \App\Category:all();返回一个类别的集合,我希望该集合根据我指定的更改来更改属性,它将像您从 all() 获得的集合一样工作,但只是属性的另一个名称。
  • 以上代码将返回集合。检查返回类型。您能否详细说明您的要求,以便我提出其他建议。
  • 集合 {#220 ▼ #items: array:2 [▼ 0 => array:3 [▼ "identificador" => 1 "nome" => "categoria1" "slug" => "categoria1 " ] 1 => array:3 [▶] ] } 它确实返回了一个集合,但里面是一个数组,而不是模型的集合,我将更改我的问题以指定它需要维护什么样的集合是的。
猜你喜欢
  • 2016-06-24
  • 2019-12-10
  • 2012-01-18
  • 2013-04-28
  • 2019-11-10
  • 1970-01-01
  • 2023-03-02
  • 1970-01-01
相关资源
最近更新 更多