手动添加项目到现有对象[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将作为一个新键追加,但我想将它插入Question中以便之后我可以像这样使用foreach $q -> test

访问它

下面是我访问item的方式:

@foreach($q as $qq)
{{ $qq->test }}
@endforeach

可以使用Eloquent Model (https://github.com/illuminate/database/blob/master/Eloquent/Model.php)的setAttribute()函数来实现。
正如您所看到的,它使用setAttribute()将数据存储在受保护的$attributes中,当我们使用$SomeModel->some_field时,它使用魔术方法__get()通过关联从attributes数组中检索项。

以下是你问题的解决方案:

$Question = Question::find($id);
$Question->setAttribute('test', 'blablabla');

除了setAttribute(),您还可以使用put()参考本文中的一个项目。关于map()的许多项目,请参考这篇文章。