手动将项目添加到现有对象 [Laravel 5]
问题描述
这是我尝试做的:
这将输出:
所以 'test' =>true
将作为新键追加,但我想将它插入 Question
中,以便以后我可以像这样使用 foreach $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:
推荐答案
可以通过使用 Eloquent Model (https://github.com/illuminate/database/blob/master/Eloquent/Model.php).
如您所见,它使用 setAttribute() 将数据存储在 protected $attributes 中,当我们执行 $SomeModel->some_field 时,它使用魔术方法__get() 从 attributes 数组中通过关联检索项目.
这是您问题的解决方案:
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:
这篇关于手动将项目添加到现有对象 [Laravel 5]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!