【问题标题】:Prepend an item at the beginning of each element of an Eloquent collection of Laravel在 Laravel 的 Eloquent 集合的每个元素的开头添加一个项目
【发布时间】:2015-06-25 06:59:04
【问题描述】:

我有这样的收藏

[
  {
    "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": [
    ...
    .....

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

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

return $new;

【问题讨论】:

  • 您能否详细说明“但没有成功”?它是否预先添加了任何内容,是否添加了令人担忧的级别或其他内容?
  • 这是我尝试过的: $new = $objectives->map(function($objective) { return $objective->get()->prepend('hello', 'wordl'); } );返回 $new;
  • 您可以编辑您的问题而不是添加评论吗?我问是因为其他人更容易看到你的尝试。

标签: php laravel collections eloquent laravel-5


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-28
    • 2022-07-21
    • 1970-01-01
    相关资源
    最近更新 更多