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
Manually add item to existing object [Laravel 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' => true
will append as a new key, but I want to insert it in Question
so 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');