Laravel 4查询内部视图

Laravel 4查询内部视图,laravel,laravel-4,Laravel,Laravel 4,在我的上一个问题中,我需要执行一个原始SQL查询 @foreach($getdeaths as $getdeath) <tr> <? $name = DB::select( DB::raw('SELECT name FROM players WHERE id = '$getdeath->player_id'') ) ?> <td>{{ $getdeath->player_id }}</t

在我的上一个问题中,我需要执行一个原始SQL查询

        @foreach($getdeaths as $getdeath)
    <tr>
        <? $name = DB::select( DB::raw('SELECT name FROM players WHERE id = '$getdeath->player_id'') ) ?>
        <td>{{ $getdeath->player_id }}</td>
        <td></td>
        <td></td>
    </tr>
    @endforeach
我已在控制器中声明了一个公共函数:

public function deaths()
{
    $getdeaths = DB::statement('SELECT * FROM player_deaths ORDER BY time DESC LIMIT 10');
    return View::make('main.latestdeaths')->with('getdeaths', $getdeaths);
}
在检索数据时,我希望显示播放器名称,因此在foreach的视图中,尝试运行SQL查询

        @foreach($getdeaths as $getdeath)
    <tr>
        <? $name = DB::select( DB::raw('SELECT name FROM players WHERE id = '$getdeath->player_id'') ) ?>
        <td>{{ $getdeath->player_id }}</td>
        <td></td>
        <td></td>
    </tr>
    @endforeach
@foreach($getdeath作为$getdeath)
{{$getdeath->player_id}
@endforeach
当我尝试回显$name时,变量没有定义


我可以用其他方式解析它吗?

您使用的是DB::select,因此必须执行get()来检索记录,顺便说一句,对视图进行SQL查询是不好的,不尊重MVC架构模式。

给您:

$getDeaths = DB::table('player_deaths')->orderBy('time','desc')->take(10)->get();
return View::make('main.latestdeaths')->with('getDeaths', $getDeaths);

这将为您提供一个按时间顺序排列的所有玩家死亡的对象。

查看视图生成器。基本上是一个过滤器或类方法,在呈现某些视图名称时调用该方法,并自动分配视图变量

告诉编写器运行查询,并为您希望在其中获得信息的视图设置deaths变量


然后,您可以在变量上循环,就像您在视图中分配了它一样。

如何才能以更好的方式执行?我知道这不好,但想不出更简单/更好的方法。谢谢。斯蒂尔,我怎样才能在视图中检索到与SQL查询相同的结果?你能告诉我你的表关系吗?我最近在一个陌生的代码中看到了这一点。为什么有人想从视图中查询?这很难看,违反了MVC惯例。请避免做这样的事情,或者习惯于开发结构化的。关于Laravel我不能说太多,但考虑到其他MVC框架,您可能会对模型关系感兴趣,这种关系很常见,并且遵循约定。要聪明。分裂逻辑。