如何使用联合来连接具有不同列名的多个表

时间:2020-11-06 15:49:10

标签: laravel

我下面的查询使用联合从两个表中进行选择,但是“ archive_pickup.pickup_id_”和“ pickup_request.id”不是相同的列名,我想输出“ archive_pickup.pickup_id_”]或“ pickup_request.id”在我看来,是基于从哪个表获得记录的,因为它们不是同一列。所以我得到一个错误,显示未定义的属性:stdClass :: $ pickup_id_(View:

我的控制器

$archive_pickup = DB::table("archive_pickup")
    ->select("archive_pickup.pickup_id_","archive_pickup.sendername","archive_pickup.recipientname",
    "archive_pickup.pickupdate","archive_pickup.pickuptime","archive_pickup.deliverytime",
    "archive_pickup.status");
  
$all_pickups = DB::table("pickup_request")
    ->select("pickup_request.id","pickup_request.sendername","pickup_request.recipientname",
    "pickup_request.pickupdate","pickup_request.pickuptime","pickup_request.deliverytime",
    "pickup_request.status")
    ->union($archive_pickup)
    ->get();
  
 return view('all_pickups',['all_pickups' => $all_pickups]);

我的观点

在我看来,由于列名不同,我如何根据检索到的记录输出从archive_pickup表获得的Pickup_id_列或从Pickup_request表获得的id列。

 @foreach($all_pickups as $all_pickup)
   <tr> 
       <td>{{ $all_pickup->pickup_id_ || $all_pickup->id}}</td>
   </tr> 
 @endforeach

1 个答案:

答案 0 :(得分:0)

尝试使用property_exists

  @foreach($all_pickups as $all_pickup)
       <tr> 
           <td>
 @if(property_exists($all_pickup,'pickup_id_'))
{{-- there is pickup_id_ --}}
@else
{{-- there is no pickup_id_ so it must be id --}}
@endif
          </td>
       </tr> 
     @endforeach