[英]Complicated query from three tables in Laravel
我有一個問題,我用Laravel無法解決。 我有三張桌子:
用戶,屬性,優惠
用戶擁有多個屬性和優惠屬性和優惠屬於用戶
Properties table:
id
user_id
contract_start_date
other_date
…
created_at
updated_at
Offers table:
id
user_id
…
created_at
updated_at
我想給一個像這樣的表(我使用兩個日期過濾器:startDate和endDate):
Users name || Properties count (They are filtered by contract_start_date) || Properties count (They are filtered by other_date) || Offers count
———
user1 || 5 || 2 || 12
user2 || 0 || 1 || 0
user3 || 0 || 0 || 0
…
我嘗試使用union,leftJoin等,但我無法解決這個問題...謝謝,如果你能提供幫助的話
首先,讓您的用戶渴望加載其屬性的日期和所有優惠。
$users = Users::with([
'property'=>function($query){
$query->select('contract_startdate','otherdate');
},
'offer'=>function($query){
$query->select('id');
},
);
假設您已在模型中正確設置$dates
數組以包含contract_startdate
和other_date
。 我們可以使用碳來過濾集合,以獲得我們感興趣的屬性。 在您看來,您可以:
<table>
<thead>
<tr>
<th>User</th>
<th>Property (start date)</th>
<th>Property (other date)</th>
<th>Offers</th>
</tr>
</thead>
<tbody>
@foreach($users as $user)
<tr>
<td>{{$user->name}}</td>
<td>{{$user->properties
->filter(function($item) use ($filter_start,$filter_end){
return $item->contract_startdate->between($filter_start,$filter_end);
})->count() }}</td>
<td>{{$user->properties
->filter(function($item) use ($filter_start,$filter_end){
return return $item->other_date->between($filter_start,$filter_end);
})->count() }}</td>
<td>{{$user->offers->count()}}</td>
</tr>
@endforeach
</tbody>
</table>
您可能應該將視圖中的過濾器重構為清晰度,但這樣做會在集合上添加另一個循環。 但是你可以通過在控制器中執行類似的操作來刪除循環。
$users = Users::with([
'property'=>function($query){
$query->select('contract_startdate','otherdate');
},
'offer'=>function($query){
$query->select('id');
},
);
$byContractDate = collect();
$byOtherDate = collect();
foreach($users as $user){
foreach($properties as $property){
$contractCounter = 0;
$otherCounter = 0;
if($propery->contract_startdate->between($filter_start,$filter_end){
$contractCounter++;
}
if($propery->contract_startdate->between($filter_start,$filter_end){
$otherCounter++;
}
}
$byContractDate->put($user->id,$contractCounter);
$byOther->put($user->id,$otherCounter);
}
在你看來:
<table>
<thead>
<tr>
<th>User</th>
<th>Property (start date)</th>
<th>Property (other date)</th>
<th>Offers</th>
</tr>
</thead>
<tbody>
@foreach($users as $user)
<tr>
<td>{{$user->name}}</td>
<td>{{$byContract->get($user->id)}}</td>
<td>{{$byOther->get($user->id)}}</td>
<td>{{$user->offers->count()}}</td>
</tr>
@endforeach
</tbody>
</table>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.