[英]Laravel Eloquent: How to select from multiple tables
我正在使用 Laravel 和它提供的 Eloquent ORM,但我正在努力选择我需要的数据。 我有3个模型
一所房子可以有多个居住者,我可以使用以下方法轻松获得这些。
$house= House::find($house_id);
$occupants = $house->occupants()->where('active', 1)->get();
这很好用,但我也想选择每个住户的工作。 我把它作为一对一的关系,但工作在一张单独的桌子上。
有没有办法有效地从工作表中为每个占用者选择相关工作? 我猜它会是这样的
$occupants_and_jobs = $house->occupants()->where('active', 1)->job()->get();
你可以试试你的建议,看看会发生什么。 您还可以对关系进行一些急切加载
$house = House::with(["occupants","occupants.job"])->find($house_id);
foreach ($house->occupants as $occupant) {
print_r($occupant->job);
}
作为@AlexeyMezenin,如果您需要限制关系,那么您需要(正如文档在Constraining Eager Loads下建议的那样)执行以下操作:
$house = House::with(["occupants" => function ($query) {
$query->where("active","=",1);
},"occupants.job"])->find($house_id);
foreach ($house->occupants as $occupant) {
print_r($occupant->job);
}
现在的细则是:Laravel 将按照它找到的顺序包含“with”关系,还包括嵌套的所有中间关系,例如::with("occupants.job")
暗示::with(["occupants","occupants.job"])
但是,如果您已经设置了以前的关系,那么它会被维护(这就是它的工作原理)。 occupants
的时候不会被覆盖occupants.job
设置。
此查询将加载active = 1
所有占用者及其工作:
House::with(['occupants' => function($q) {
$q->where('active', 1);
}, 'occupants.job'])->find($house_id);
在laravel中从不同表中搜索数据的完整方法:
路线:
Route::get('/systems/search', 'SearchController@search')->name('project-search');
在您的 searchController 中尝试这种方式:
public function search(Request $request)
{
$data = DB::table('projects as p')->select('p.*','u.first_name', 'u.last_name')
->join('users as u','p.user_id','=','u.id');
if( $request->input('search')){
$data = $data->where('p.title', 'LIKE', "%" . $request->search . "%")
->orWhere('p.description', 'LIKE', "%" . $request->search . "%")
->orWhere('u.first_name', 'LIKE', "%" . $request->search . "%")
->orderBy('p.created_at', 'desc');
}
$data = $data->paginate(16);
return view('systems.search', compact('data'));
}
并以这种方式在您的刀片中接收这些数据:
<div class="col-md-8">
<h3>List of Results</h3>
<table class="table table-striped">
<tr>
<th>title</th>
<th>description</th>
<th>creator</th>
<th>category</th>
</tr>
@foreach($data as $search)
<tr>
<td>{{ $search->title }}</td>
<td>{{ $search->description }}</td>
<td>{{ $search->first_name }}</td>
</tr>
@endforeach
</table>
{{ $data->appends(request()->except('page'))->links() }}
</div>
搜索框输入字段:
<div class="input-group input_search" style="width: 100%">
<input style="border-radius: 20px" type="text" class="form-control search"
placeholder="Search" aria-describedby="basic-addon2" name="search" id="search"
value="{{Request::get('title')}}">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.