我从数据库查询并返回数组
$games = Game::where('admin_id', $user->id)->where('active', true)->get();
现在我尝试在 $games
数组中添加对象,如下所示
$games->push(['name' => 'Game1', 'color' => 'red']); //its adding array instead object
请解释一下,谢谢
最佳答案
因为你推送了一个数组
,所以它正在添加数组。
// here, you are pushing the array so you get the array.
['name' => 'Game1', 'color' => 'red']
像这样插入物体:
$games = $games->push(new Game(['name' => 'Game1', 'color' => 'red']));
或者这样:
$games = $games->push((object)['name' => 'Game1', 'color' => 'red']);
关于laravel - 如何将对象推送到数组laravel php中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63696341/