当前位置:Gxlcms > PHP教程 > laravel5中关联查询

laravel5中关联查询

时间:2021-07-01 10:21:17 帮助过:25人阅读

有这么一组数据

一个学生表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

人气教程排行