首页 > 解决方案 > 此集合实例上不存在属性 [lesson_id] - 即使我使用的是 foreach,因此仅检索 1 个模型

问题描述

我有一个简单的 LessonUser 表和模型 - 3 列 + 时间戳。

我正在使用 Laravel 8 并做 TDD。

我从表中获取一些数据:

/** get the latest lessonUser for each lesson_id */
    $latestUserLessons =
        LessonUser::
            select('user_id', 'lesson_id', 'status_id')
            ->where('user_id', $user)
            ->latest()
            ->get()
            ->groupBy('lesson_id')
            ;

如果我运行这个:

        foreach ($latestUserLessons as $latestUserLesson)
               {
                    dd($latestUserLesson);
               }

我得到:

Illuminate\Database\Eloquent\Collection {#2731
  #items: array:1 [
    0 => App\Models\LessonUser {#2741
      #guarded: []
      #connection: "mysql"
      #table: "lesson_users"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:3 [
        "user_id" => 1
        "lesson_id" => 1
        "status_id" => 1
      ]
      #original: array:3 [
        "user_id" => 1
        "lesson_id" => 1
        "status_id" => 1
      ]
      #changes: []
      #casts: []
      #classCastCache: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #fillable: []
    }
  ]
}

所以我显然有'lesson_id'属性。

但是当我运行这个时:

        foreach ($latestUserLessons as $latestUserLesson)
        {
            dd($latestUserLesson->lesson_id);
        }

我得到了可怕的:

Property [lesson_id] does not exist on this collection instance.
  at C:\xampp\htdocs\tdd\vendor\laravel\framework\src\Illuminate\Collections\Traits\EnumeratesValues.php:850
    846▕      */
    847▕     public function __get($key)
    848▕     {
    849▕         if (! in_array($key, static::$proxies)) {
  ➜ 850▕             throw new Exception("Property [{$key}] does not exist on this collection instance.");
    851▕         }
    852▕
    853▕         return new HigherOrderCollectionProxy($this, $key);
    854▕     }
  1   C:\xampp\htdocs\tdd\app\Http\Controllers\SeshController.php:30
      Illuminate\Support\Collection::__get("lesson_id")
  2   C:\xampp\htdocs\tdd\vendor\laravel\framework\src\Illuminate\Routing\Controller.php:54
      App\Http\Controllers\SeshController::buildSesh()
  Tests:  1 failed
  Time:   1.17s

我知道如果我尝试从集合中获取属性,我会收到此错误,但这里我显然有一个模型实例。我尝试过:使用 eloquent 进行数据检索;使用带有增量的'for'循环,最多检索模型的计数,控制数组位移等,我只是不断收到相同的错误。

我错过了什么吗?还有其他方法可以获取该字段数据吗?

嘎嘎!!帮助!!

标签: phplaravelcollectionsproperties

解决方案


你有一个集合的集合。您必须迭代集合和嵌套在其中的集合以获取 LessonUser 模型。

foreach ($latestUserLessons as $group) {
    foreach ($group as $latestUserLesson) {
        dd($latestUserLesson->lesson_id);
    }
}

推荐阅读