Manually add item to existing object [Laravel 5](手动将项目添加到现有对象 [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 将作为新键追加,但我想将它插入 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:
@foreach($q as $qq)
{{ $qq->test }}
@endforeach
推荐答案
可以通过使用 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:
$Question = Question::find($id);
$Question->setAttribute('test', 'blablabla');
这篇关于手动将项目添加到现有对象 [Laravel 5]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:手动将项目添加到现有对象 [Laravel 5]
基础教程推荐
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 如何替换eregi() 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
