手动添加项目到现有的对象[Laravel 5] [英] Manually add item to existing object [Laravel 5]
问题描述
这是我尝试做的:
$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
将附加为新的键,但是我想将它插入到问题
中,所以后来我可以使用foreach访问它$ c> $ q - >测试
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
所以这里是我想要访问项目:
So here is how I want access to item:
@foreach($q as $qq)
{{ $qq->test }}
@endforeach
推荐答案
可以使用Eloquent Model的 setAttribute()函数来完成( https://github.com/illuminate/database/blob/master/Eloquent/Model.php )。
如您所见,它使用 setAttribute()将数据存储在受保护的$ attributes 中,当我们执行 $ SomeModel-> some_field ,它使用魔术方法 __ get()从属性数组中关联检索项目。
这是你的问题的解决方案:
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 $attributes using setAttribute(), and when we do $SomeModel->some_field it uses magic method __get() to retrieve item by association from attributes array.
Here is the resolution to Your question:
$Question = Question::find($id);
$Question->setAttribute('test', 'blablabla');
这篇关于手动添加项目到现有的对象[Laravel 5]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!