laravel - 如何在数组laravel php中推送对象
问题描述
我从数据库查询并返回数组
$games = Game::where('admin_id', $user->id)->where('active', true)->get();
现在我正在尝试$games
像这样在数组中添加对象
$games->push(['name' => 'Game1', 'color' => 'red']); //its adding array instead object
请解释 谢谢
解决方案
因为你推了一个array
,所以它正在添加数组。
// 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']);
推荐阅读
- java - 当我从 Main2Activity.java 转到 Main3Activity.java 时,我不断收到错误消息:“testapp 已停止”
- python - 当 scipy.integrate.odeint 中的输出达到 0 时停止积分
- html - 是否建议使用像 .text-center 这样的简单 CSS 类?
- kotlin - Kotlin - 在为 setSpans() 声明开始、结束和标志时,为 SpannableStringBuilder 创建没有重复参数的自定义 ext 函数
- ios - 电话号码 (CordovaCallNumberPlugin) 在 ios 12 上不起作用
- java - 如何通过 JDBC 查询 Oracle 的交集
- python - 使用 Djongo 连接器将 Django 连接到 MongoDB 会引发 SSL 握手异常
- nativescript - 控件属性设置为 false 后,ActivityIndicator 不会关闭
- c# - 使用存储文件夹播放 .mp3 UWP
- https - HTTPS 负载均衡器,用于在 Google Kubernetes 上公开工作负载