Manually add item to existing object [Laravel 5]

杀马特。学长 韩版系。学妹 提交于 2019-12-22 03:37:28

问题


Here is what I try to do:

$q = Question::where('id',$id -> id)->get();
$q[] = $q->push([ 'test' => true]); 
dd($q);

This will output:

Collection {#220 ▼
  #items: array:3 [▼
    0 => Question {#225 ▶}
    1 => array:1 [▼
      "test" => true
    ]
    2 => null
  ]
}

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

回答1:


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



回答2:


Apart from setAttribute(), you can use put() refer to this post for one item. And map() for many items, refer to this post.



来源:https://stackoverflow.com/questions/31474452/manually-add-item-to-existing-object-laravel-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!