首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从数据库中获取国家列表,并尝试在null上读取属性"country_name“

从数据库中获取国家列表,并尝试在null上读取属性"country_name“
EN

Stack Overflow用户
提问于 2021-06-15 15:24:08
回答 1查看 582关注 0票数 0

当我试图在Laravel 8上展示我的学生时,我遇到了一些错误,首先不是创建学生,然后我在/ show /页面上出现了错误

试图在null上读取属性"country_name“

index.blade.php

代码语言:javascript
复制
  <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>

学生模型

代码语言:javascript
复制
    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);
    }

}

国家模式

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

studentController

代码语言:javascript
复制
 public function index(Request $request)
{
    $students = Student::paginate(50);
    $countries = DB::table('countries')->get();
    return view('students.index', compact( 'students','countries'));
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-06-15 15:33:48

既然foreignKey不是laravel公约,所以你必须提到foreignKey in belongsTo.I相信foreignKey is country in Student Table

代码语言:javascript
复制
public function countries()
{
    return $this->belongsTo(Country::class,'country','id');
}

和乡村模式

代码语言:javascript
复制
 public function student()
    {
        return $this->hasMany(Student::class,'country','id');
    }

然后你可以访问

代码语言:javascript
复制
 $students = Student::with('countries')->paginate(50);

BelongsTo方法描述

代码语言:javascript
复制
belongsTo($related, $foreignKey = null, $ownerKey = null, $relation = null)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67989124

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档