0

在尝试在 Laravel 8 上创建展示我的学生时,我遇到了一些错误,首先它没有创建学生,然后我在 /students/ 页面上遇到错误

尝试在 null 上读取属性“country_name”

index.blade.php

  <tbody id="allocate-table-body">
                                        @foreach($students as $student)
                                        <tr class="id-card">
                                            <td><a target="_blank"  href=""> {{$student->id}}</a></td>
                                            <td> {{$student->name}}</td>
                                            <td>{{$student->countries->country_name}}</td>
                                            <td>{{$student->phone}}</td>
                                            <td>{{$student->work}}</td>
                                            <td>{{$student->group}}</td>
                                            <td>{{$student->email}}</td>
                                            <td><a class="btn btn-success" href="#">edit</a></td>
                                        </tr>
                                        @endforeach
                                        </tbody>

学生模型

    class Student extends Model
{
    use HasFactory;
    public $fillable = [
        'name',
        'marital',
        'gender',
        'country',
        'city',
        'education',
        'work',
        'phone',
        'group',
        'email',
        'description'
    ];
    public function countries()
    {
        return $this->belongsTo(Country::class);
    }

}

国家模式

    class Country extends Model
{
    protected $fillable = ['id', 'phone_code', 'country_code', 'country_name'];
    use HasFactory;
    public function student()
    {
        return $this->hasMany(Student::class);
    }
}

学生控制器

 public function index(Request $request)
{
    $students = Student::paginate(50);
    $countries = DB::table('countries')->get();
    return view('students.index', compact( 'students','countries'));
}
4

1 回答 1

0

由于foreignKey 不是 laravel 约定,所以您必须foreignKeybelongsTo.我相信 foreignKeycountry中提及Student Table

public function countries()
{
    return $this->belongsTo(Country::class,'country','id');
}

在国家模式中

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

然后就可以访问了

 $students = Student::with('countries')->paginate(50);

BelongsTo 方法说明

belongsTo($related, $foreignKey = null, $ownerKey = null, $relation = null)
于 2021-06-15T15:33:48.627 回答