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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31474452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:27:27  来源:igfitidea点击:

Manually add item to existing object [Laravel 5]

phparrayscollectionseloquentlaravel-5

提问by Vladimir Djukic

Here is what I try to do:

这是我尝试做的:

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

This will output:

这将输出:

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

So 'test' => truewill append as a new key, but I want to insert it in Questionso latter I can access to it like this with foreach $q -> test

所以'test' => true将附加为一个新的键,但我想将它插入到Question后者中,我可以像这样使用 foreach 访问它$q -> test

So here is how I want access to item:

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

@foreach($q as $qq)
{{ $qq->test }}
@endforeach

回答by num8er

It can be done by using setAttribute()function of Eloquent Model (https://github.com/illuminate/database/blob/master/Eloquent/Model.php).
As You can see it stores data in protected $attributesusing setAttribute(), and when we do $SomeModel->some_fieldit uses magic method __get()to retrieve item by association from attributesarray.

Here is the resolution to Your question:

可以通过使用Eloquent 模型 ( https://github.com/illuminate/database/blob/master/Eloquent/Model.php) 的setAttribute()函数来完成。 如您所见,它使用setAttribute()将数据存储在受保护的 $attributes 中,当我们执行$SomeModel->some_field 时,它使用魔术方法__get()属性数组中通过关联检索项目。 这是您问题的解决方案:


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

回答by Kris Roofe

Apart from setAttribute(), you can use put()refer to this postfor one item. And map()for many items, refer to this post.

除了setAttribute(),您可以使用put()参考这篇文章的一个项目。而map()对于许多项目,请参阅此职位