laravel - 如何将对象推送到数组laravel php中

标签 laravel laravel-collection

我从数据库查询并返回数组

$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/

相关文章:

php - Laravel中如何使用groupby结果统计记录数?

php - 在 laravel 的关系表中保存数据时出错

php - Laravel 集合 sortBy 没有生效

php - Eloquent 合集 : each vs foreach

php - 可能在 Flash 消息中有一个链接

laravel - 在laravel中创建项目时,Symfony在output.php中解析错误

php - 拉拉维尔 5.5 : Authorization with pivot table

json - 如何将 Laravel 集合数组转换为 json

mysql - 如何在 laravel 集合中添加额外元素

php - 如何在 Laravel 中自定义对象集合