在视图上显示数据时尝试获取 属性 'column_name' 的 non-object

Trying to get property 'column_name' of non-object while displaying data on view

我想在我的 blade 视图中显示来自关系数据的数据,但是当我尝试显示数据时,而 table 只包含一行数据,它在视图中显示,但如果我插入超过table 中的一个数据给我一个错误。

我有三个 table coursessectionscourse_section。在 course_section table 中,这些是以下列 course_idsection_id.

我已经尝试 {{ $section->courses()->first()->courseTitle }} 在 Whosebug 上找到的视图中的这个片段。

我的部分模型代码:-

class section extends Model
{
  public function courses(){
    return $this->belongsToMany('App\Model\admin\course\course','course_sections','course_id');
  }
}

我的部门控制器代码:-

$sections = section::with('courses')->orderBy('id','DESC')->get();
      return view('backend.courses.section.all',compact('sections','courses'));

我的查看代码:-

@foreach ($sections as $section)
          <tr>
            <td>{{ $section->title }}</td>
            <td>{{ $section->courses()->first()->courseTitle }}</td>
          </tr>
@endforeach

我遇到了这个错误

"Trying to get property 'courseTitle' of non-object (View: resources/views/backend/courses/section/all.blade.php)"

部门负责人:

$sections = section::with('courses')->orderBy('id','DESC')->get();
return view('backend.courses.section.all', compact('sections'));

在视图中,您必须循环显示部分,然后循环显示课程并创建每一行。例如:

@foreach ($sections as $section)
    @foreach ($section->courses as $course)
          <tr>
            <td>{{ $section->title }}</td>
            <td>{{ $course->courseTitle }}</td>
          </tr>
    @endforeach
@endforeach

注意是$section->courses而不是$section->courses(),因为相关的课程已经有了,不用再查询了。


更新

或者您可以通过 course

进行查询
$courses = course::with('sections')->get();
return view('backend.courses.section.all',compact('courses'));

在视图中:

@foreach ($courses as $course)
    @foreach ($course->sections as $section)
          <tr>
            <td>{{ $section->title }}</td>
            <td>{{ $course->courseTitle }}</td>
          </tr>
    @endforeach
@endforeach

以下是你做错的地方:

  1. $section->courses() 替换为 $section->courses,因为您已经在进行早期加载。 $section->courses() 将再次查询数据库。

  2. 检查关系数据是否存在然后显示。

所以你的代码如下:

@foreach ($sections as $section)
<tr>
    <td>{{ $section->title }}</td>
    <td>
        @php
           $course = $section->courses->first();
        @endphp

        {{ $course->courseTitle or "" }}
    </td>
</tr>
@endforeach

如果有帮助请告诉我!

已编辑:

根据对话,关系已更改为 course ->hasMany -> sectionssection ->belongsTo -> course,因此 blade 将更改为

@foreach ($sections as $section)
<tr>
    <td>{{ $section->title }}</td>
    <td>
        @php
           $course = $section->course;
        @endphp

        {{ $course->courseTitle or "" }}
    </td>
</tr>
@endforeach