这是我尝试做的:
$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]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
PHP、MySQL PDOException 的死锁异常代码?Deadlock exception code for PHP, MySQL PDOException?(PHP、MySQL PDOException 的死锁异常代码?)
PHP PDO MySQL 可滚动游标不起作用PHP PDO MySQL scrollable cursor doesn#39;t work(PHP PDO MySQL 可滚动游标不起作用)
PHP PDO ODBC 连接PHP PDO ODBC connection(PHP PDO ODBC 连接)
使用 PDO::FETCH_CLASS 和魔术方法Using PDO::FETCH_CLASS with Magic Methods(使用 PDO::FETCH_CLASS 和魔术方法)
php pdo 只从 mysql 获取一个值;等于变量的值php pdo get only one value from mysql; value that equals to variable(php pdo 只从 mysql 获取一个值;等于变量的值)
MSSQL PDO 找不到驱动程序MSSQL PDO could not find driver(MSSQL PDO 找不到驱动程序)