欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

laravel5 中 关联查询

程序员文章站 2022-06-06 14:11:27
...
有这么一组数据

一个学生表users 和 学生成绩表 grades 两个表关联

在方法里面是这样的

public function index()
{
    $result = User::where('is_admin', 0);
    $users = $result->get();
    $count = $result->count();       
    return view('admin.list', compact('count', 'users'));
}

视图循环是这样的

 @foreach ($users as $user)
    
{{$user->id}}
        {{$user->name}}
        {{$user->grade->math}}
        {{$user->grade->english}}
        {{$user->grade->c}}
        {{$user->grade->sport}}
        {{$user->grade->think}}
        {{$user->grade->soft}}
    
@endforeach

得到的结果是 报错 Trying to get property of non-object (View:

$user->grade->math

是找不到的 怎么做关联一起呢

回复内容:

有这么一组数据

一个学生表users 和 学生成绩表 grades 两个表关联

在方法里面是这样的

public function index()
{
    $result = User::where('is_admin', 0);
    $users = $result->get();
    $count = $result->count();       
    return view('admin.list', compact('count', 'users'));
}

视图循环是这样的

 @foreach ($users as $user)
    
{{$user->id}}
        {{$user->name}}
        {{$user->grade->math}}
        {{$user->grade->english}}
        {{$user->grade->c}}
        {{$user->grade->sport}}
        {{$user->grade->think}}
        {{$user->grade->soft}}
    
@endforeach

得到的结果是 报错 Trying to get property of non-object (View:

$user->grade->math

是找不到的 怎么做关联一起呢

User.php

public function grade()
    {
        return $this->hasOne('App\Grade');
    }

Grade.php

public function user()
    {
        return $this->belongsTo('App\User');
    }

phpUser.php定义
public function Grade()
    {
        return $this->hasOne("App\Modules\Grade", 'user_id', 'id');
    }
controller.php
public function index()
{
    $result = User::where('is_admin', 0);
    $users = $result->grade()->get();
    $count = $result->count();       
    return view('admin.list', compact('count', 'users'));
}

view:
@foreach ($users as $user)
    
{{$user->id}}
        {{$user->name}}
        {{$user->math}}
        {{$user->english}}
        {{$user->c}}
        {{$user->sport}}
        {{$user->think}}
        {{$user->soft}}
    
@endforeach