首页 > 解决方案 > “此集合实例上不存在属性 [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"
    }
  ]
}

标签: phpdatabaselaraveleloquentlaravel-blade

解决方案


正如dd暗示的那样,您$currentUser包含 a collection,因此它不是一条记录。您必须遍历其内容才能获得单个用户。像这样的东西:

@foreach ($currentUser as $user)
    {{ $user->id }}
@endforeach

推荐阅读