从数据库中获取国家列表并尝试读取 属性 "country_name" on null

Get Country list from database and get Attempt to read property "country_name" on null

在 Laravel 8 上尝试创建 show my students 时遇到了一些错误,首先不是创建学生,然后我在 /students/ page

上遇到错误

Attempt to read property "country_name" on null

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'));
}

因为 foreignKey 不是 laravel 约定所以你必须在 belongsTo 中提到 foreignKey。我相信 foreignKey 在 Student Table 中是 country

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)