手动将项目添加到现有对象 [Laravel 5]

2021-12-26 00:00:00 arrays collections php laravel-5 eloquent

这是我尝试做的:

$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');

相关文章