手动将项目添加到现有对象 [Laravel 5]

问题描述 投票:0回答:3

这是我尝试做的:

$q = Question::where('id',$id -> id)->get();
$q[] = $q->push([ 'test' => true]); 
dd($q);

这将输出:

Collection {#220 ▼
  #items: array:3 [▼
    0 => Question {#225 ▶}
    1 => array:1 [▼
      "test" => true
    ]
    2 => null
  ]
}

所以

'test' => true
将作为新键追加,但我想将其插入到
Question
中,以便稍后我可以使用 foreach 来访问它
$q -> test

这就是我想要访问项目的方式:

@foreach($q as $qq)
{{ $qq->test }}
@endforeach
php arrays collections eloquent laravel-5
3个回答
47
投票

可以使用 Eloquent Model 的 setAttribute() 函数来完成(https://github.com/illustrate/database/blob/master/Eloquent/Model.php)。
正如您所看到的,它使用 setAttribute() 将数据存储在 protected $attributes 中,当我们执行 $SomeModel->some_field 时,它使用魔术方法 __get() 通过关联从 attributes 数组中检索项目。

这是您问题的解决方案:

$Question = Question::find($id);
$Question->setAttribute('test', 'blablabla');

6
投票

除了

setAttribute()
之外,您还可以使用
put()
参考此post来购买一项。
map()
对于许多项目,请参阅此帖子


0
投票

只需添加这样的新属性

$Q = Question::find($id);
$Q->new_attribute = 'data';

在 foreach 中:

foreach($questions as $k=>$q){
   $q->new_attribute = 'data';
   $questions[$k] = $q;
}
© www.soinside.com 2019 - 2024. All rights reserved.