laravel5 中 关联查询
有这么一组数据
一个学生表
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)
<tr>
<td>{{$user->id}}</td>
<td>{{$user->name}}</td>
<td>{{$user->grade->math}}</td>
<td>{{$user->grade->english}}</td>
<td>{{$user->grade->c}}</td>
<td>{{$user->grade->sport}}</td>
<td>{{$user->grade->think}}</td>
<td>{{$user->grade->soft}}</td>
</tr>
@endforeach
得到的结果是 报错
Trying to get property of non-object (View:
$user->grade->math
是找不到的 怎么做关联一起呢
西红柿妖梦
9 years, 4 months ago
Answers
php
User.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) <tr> <td>{{$user->id}}</td> <td>{{$user->name}}</td> <td>{{$user->math}}</td> <td>{{$user->english}}</td> <td>{{$user->c}}</td> <td>{{$user->sport}}</td> <td>{{$user->think}}</td> <td>{{$user->soft}}</td> </tr> @endforeach
魅惑喵翔翎
answered 9 years, 4 months ago