[英]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.