Laravel 5 将数据库查询从控制器传递到视图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30555747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 5 passing database query from controller to view
提问by Scudder Stevens
I'm new to Laravel 5 and MVC frameworks in general. I having trouble getting results from a database query and passing it to my blade view. Here is what I have for a controller function ...
我是 Laravel 5 和 MVC 框架的新手。我无法从数据库查询中获取结果并将其传递给我的刀片视图。这是我对控制器功能的看法......
public function show(Project $project)
{
$technologies = DB::select('select * from technologies where id = ?', [$project->technology_id]);
return view('projects.show', compact('project','technologies'));
}
and my view is ...
我的观点是......
@section('content')
<h2>{{ $project->name }}</h2>
@if ( !technologies() )
no technologies.
@else
<ul>
@foreach( $technologies as $technology )
<li><a href="#">{{ $technology->slug }}</a></li>
@endforeach
</ul>
@endif
@endsection
Thanks for your help
谢谢你的帮助
回答by haakym
controller
控制器
public function show(Project $project)
{
$technologies = DB::table('technologies')
->select('*')
->where('id', $project->technology_id)
->get(); // you were missing the get method
return view('projects.show', compact('project', 'technologies'));
}
View
看法
This will not work in your view: @if ( !technologies() )
这在您看来是行不通的: @if ( !technologies() )
@section('content')
<h2>{{ $project->name }}</h2>
@if($technologies)
<ul>
@foreach($technologies as $technology)
<li><a href="#">{{ $technology->slug }}</a></li>
@endforeach
</ul>
@else
<p>no technologies.</p>
@endif
@stop
Also, if you're interested in a cleaner way to loop through your data or show a 'no data' warning using blade check out this article which uses blade's @each https://laravel-news.com/2014/09/laravel-blade/
此外,如果您对更简洁的方式循环遍历数据或使用刀片显示“无数据”警告感兴趣,请查看这篇文章,该文章使用刀片的 @each https://laravel-news.com/2014/09/laravel -刀刃/
回答by Mohammed Safeer
rewrite your query as,
将您的查询重写为,
$technologies = DB::table('technologies')->where('id',$project->technology_id)->get();