Home  >  Article  >  Backend Development  >  laravel5 中 关联查询

laravel5 中 关联查询

WBOY
WBOYOriginal
2016-06-06 20:33:301442browse

有这么一组数据

一个学生表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>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn