Laravel中三个表的复杂查询

时间:2019-04-24 18:02:56

标签: php sql 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等,但是我无法解决此问题…… 谢谢,如果可以的话

1 个答案:

答案 0 :(得分:0)

快速和肮脏

首先,让您的用户渴望加载其属性的日期和所有优惠。

$users = Users::with([
    'property'=>function($query){
        $query->select('contract_startdate','otherdate');
    },
    'offer'=>function($query){
        $query->select('id');
    },
);

假设您已在模型中正确设置$dates数组以包含contract_startdateother_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>