如何解决从数据库中获取国家列表并尝试在 null 上读取属性“country_name”
尝试在 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'));
}
解决方法
由于 is_a_palindrome = word == "".join(reversed(word))
不是 laravel 约定,所以您必须在 foreignKey
中提及 foreignKey
。我相信 belongsTo
中的外键是 country
Student Table
国内模式
public function countries()
{
return $this->belongsTo(Country::class,'country','id');
}
然后就可以访问了
public function student()
{
return $this->hasMany(Student::class,'id');
}
BelongsTo 方法说明
$students = Student::with('countries')->paginate(50);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。