在Laravel的Eloquent集合的每个元素的开头添加一个项目

时间:2015-04-18 10:17:08

标签: php laravel collections eloquent laravel-5

我有一个像这样的集合

[
  {
    "objective_id": "26",
    "objective_weight": "50.00",
    "objective_description": "This is first strategic objective",
    "actions": [
    ]
  },
  {
    "objective_id": "27",
    "objective_weight": "12.00",
    "objective_description": "This second strategic objective",
    "actions": [
    ]
  },

]

现在我想为集合的每个元素添加一个项目。 例如:

[
  {
    "foo" : "bar"
    "objective_id": "26",
    "objective_weight": "50.00",
    "objective_description": "This is first strategic objective",
    "actions": [
    ...
    .....

我尝试使用prepend() Eloquent方法,但没有成功。

$new = $objectives->map(function($objective) {
    return $objective->get()->prepend('hello', 'world');
});

return $new;

1 个答案:

答案 0 :(得分:3)

这些项目只是对象,您可以通过设置它来添加属性:

$new = $objectives->map(function($objective){
    $objective->foo = 'bar';
    return $objective;
});