一对多关系“此集合实例上不存在属性”

时间:2018-12-28 22:14:02

标签: laravel eloquent relationship

我正在尝试使用一对多关系填充表中的列

///这是我的看法Student.blade.php ////

@foreach($student as $students)
 <tr role="row" class="odd">
   <td class="sorting_1">{{$students->id}}</td>
   <td><img src="/img/{{$students->photo}}"
       style="width: 50px; height: 50px; border-radius: 50%;">
   </td>
    <td>{{$students->matric_no}}</td>
    <td>{{$students->first_name}}</td>
    <td>{{$students->last_name}}</td>
    <td>{{$students->gender}}</td>
    <td>{{$students->DOB}}</td>
    <td>{{$students->classrm->id}}</td>

///学生模型////

public function classrm(){
        return $this->belongsTo(Classroom::class);
    }

///类模型////

public function student(){
        return $this->hasMany(Student::class);
    }

///学生控制器///

public function index()
    {
        $student = Student::all();
        return view('student.Index', compact('student'));
    }

我希望它显示我数据库中的值,但是会抛出异常,试图获取非财产的ID

1 个答案:

答案 0 :(得分:0)

只需在您的学生模型中将您的关系的名称更改为classroom

public function classroom(){
    return $this->belongsTo(Classroom::class);
}