目前我有一个搜索表单,我可以在其中查询我的数据库' Batsmen"关于他们的名字和国籍。这在显示匹配约束的击球手方面工作得很好但是我试图创建的是一些告诉用户他们搜索的内容的文本。目前我可以返回nationality_ID的id值,但我想返回该nationality_id的名称字段,这是我到目前为止所拥有的:
表格:击球手::ID,姓名,国籍_ID; 国籍:ID,姓名, 评论:ID,评论,batsmen_id
搜索表单:
{!! Form::open(['route' => 'search.index', 'method' => 'GET']) !!}
<div class="form-group">
{!! Form::label('batsmenname', 'Search By Name:') !!}
{!! Form::text('batsmenname', null, array('class' => 'form-control')) !!}
</div>
</div>
<div class="col-md-6">
<div class="form-group">
{!! Form::label('nationality_id', 'Search By Nation:') !!}
<select class="form-control" name="nationality_id" >
<option value=""></option>
@foreach($nationality as $nation)
<option value="{{$nation->id}}">{{$nation->name}}</option>
@endforeach
</select>
</div>
<div class="form-group">
{!! Form::submit('Find Batsmen', array('class' => 'btn-send btn-lg btn-block')) !!}
{!! Form::close() !!}
</div>
控制器:
public function index(Request $request)
{
$batsmenQuery = Batsmen::where('approved', '=', 1)
$nationality = Nationality::all()->sortBy('name') ;
$batname=$request->input('batsmenname');
$location=$request->input('nationality_id');
if(!empty($batname)){
$batsmenQuery->where('batsmenname', 'LIKE', '%'.$batname.'%')->get();
}
if(!empty($location)){
$batsmenQuery->where('nationality_id', $request->input('categories_id') )->get();
}
$batsmen= $batsmenQuery->paginate(40);
return view('page.search')->withBatsmen($batsmen)->withBatname($batname)->withLocation($location)
}
击球手模特:
public function nationality(){
return $this->belongsTo('App\Nationality','nationality_id');
}
结果HTML:
<h4 class="result">{{($batsmen->total())}} batsmen found matching your search criteria: ('{{$batname}}', {{$location}})</p>
问题是如何获取$ location中显示的ID号码,以显示正在显示的该国籍/ ID的名称字段?
答案 0 :(得分:1)
找到您搜索的Nationality
的{{1}}模型:
nationality_id
将其更改为正确的复数形式:
if ($nationality = Nationality::find($request->input('nationality_id'))) {
$nationality_name = nationality->getAttribute('name');
} else {
abort(404, 'No matching nationality for id ' . $request->input('nationality_id') . ' found.');
}
将其返回视图:
$nationalities = Nationality::all()->sortBy('name') ;
然后在您看来,使用:
return view('page.search',compact('batsmen', 'batname', 'nationalities', 'nationality_name'));
而不是:
{{ $nationality_name }}
像这样:
{{ $location }}
我也将total()更改为count()。