php - “此集合实例上不存在属性 [id]”但代码正确吗?
问题描述
我正在使用 Eloquent ORM,在用户(玩家)和房间(会话)之间具有多对多(n 到 n)关系,其中用户连接到一个房间。他们能够打牌(scrum),以便通过他们的卡片估计来评估软件问题。
当我加载使用可选 {{id?}} 参数的视图时,它会查看我的 DB::Class 并通过参数找到房间。
问题是,当我想访问附加用户的 id 属性以在我的视图中显示接收到的信息时。虽然我的调试显示我收到了正确的数据,但我得到了上面提到的错误。
我的观点:“cards.blade.php”
<h1 align="center"><u>Userid</u> {{$currentUser->id}}</h1>
<h1 align="center"><u>Username:</u> {{$currentUser->name}}</h1>
<h1 align="center"><u>Your estimation is:</u> {{$currentUser->userValue}}</h1>
<h1 align="center">Last updated: {{$currentRoom->updated_at->diffForHumans() ?? ''}}</h1>
<h1 align="center">@if ($currentUser->isAdmin === 0 || null )
'You are sadly not an admin'
@else 'You are an admin'
@endif</h1>
<h1 align="center">Room Number: {{$currentRoom->id}}</h1>
“SessionController.php@getPlayerInfo”
public function getPlayerInfo($id)
{
$currentRoom = Session::findOrFail($id);
$currentUser = $currentRoom->users;
$tmp = $currentUser->id;
dd($currentUser);
return view('sessions.cards')
->with('currentUser', $currentUser)
->with('currentRoom', $currentRoom);
}
“web.php”
Route::get('play/{id?}', 'SessionController@getPlayerInfo')
->name('sessions.cards')
->middleware('auth');
dd($currentUser) 输出:
Collection {#305 ▼
#items: array:1 [▼
0 => User {#302 ▼
#fillable: array:3 [▶]
#hidden: array:2 [▶]
#casts: array:1 [▶]
#connection: "mysql"
#table: "users"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:10 [▼
"id" => 1
"name" => "admin"
"email" => "admin@email.com"
"email_verified_at" => null
"password" => "$2y$10$AhpAyD2NR2TW.kBYOMzTAe1kfRh73CtMhRxaGH0Bi2OrhPcSA65f."
"userValue" => null
"isAdmin" => null
"remember_token" => null
"created_at" => "2019-11-13 10:13:20"
"updated_at" => "2019-11-13 10:13:20"
]
#original: array:12 [▶]
#changes: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: array:1 [▶]
#touches: []
+timestamps: true
#visible: []
#guarded: array:1 [▶]
#rememberTokenName: "remember_token"
}
]
}
解决方案
正如dd
暗示的那样,您$currentUser
包含 a collection
,因此它不是一条记录。您必须遍历其内容才能获得单个用户。像这样的东西:
@foreach ($currentUser as $user)
{{ $user->id }}
@endforeach
推荐阅读
- python - 如何将相应的样本添加在一起?
- node.js - Node.JS 可以集成到 Flutter 移动应用程序中吗?
- python - 防止 python 脚本在没有用户输入任何可选参数的情况下运行
- php - 将查询结果计数用于验证规则(即使为空)
- jquery - jQuery 应用了两个 CSS 类,一个是应用我的格式,一个不是
- binary - 如何实现 AND/OR 语句逻辑?
- java - 将对象传递给数组的不同类型
- java - 如何从列表中检索下一个 CompletableFuture?
- html - 当该文件加载到浏览器上时,是否有任何工具可以检测/提取将从 HTML 文件中联系的域?
- python-3.x - ChatterBot 没有接受过 ubuntu 语料库的训练