Heim > Artikel > Backend-Entwicklung > laravel5 中 关联查询
有这么一组数据
一个学生表users
和 学生成绩表 grades
两个表关联
在方法里面是这样的
<code>public function index() { $result = User::where('is_admin', 0); $users = $result->get(); $count = $result->count(); return view('admin.list', compact('count', 'users')); } </code>
视图循环是这样的
<code> @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 </code>
得到的结果是 报错 Trying to get property of non-object (View:
<code>$user->grade->math </code>
是找不到的 怎么做关联一起呢
有这么一组数据
一个学生表users
和 学生成绩表 grades
两个表关联
在方法里面是这样的
<code>public function index() { $result = User::where('is_admin', 0); $users = $result->get(); $count = $result->count(); return view('admin.list', compact('count', 'users')); } </code>
视图循环是这样的
<code> @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 </code>
得到的结果是 报错 Trying to get property of non-object (View:
<code>$user->grade->math </code>
是找不到的 怎么做关联一起呢
User.php
<code>public function grade() { return $this->hasOne('App\Grade'); } </code>
Grade.php
<code>public function user() { return $this->belongsTo('App\User'); } </code>
<code>php</code><code>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 </code>