Qyouu
快速与肮脏首先,让您的用户渴望加载其属性的日期和所有报价。$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>