簡體   English   中英

在laravel模型中使用關系如何獲取刀片文件中的數據?

[英]Using relationship in laravel models how to get the data in blade file?

我用兩個表查詢數據庫中的數據。

  1. 負載:
    • LoadId
    • OriginStopId
    • DestStopId
  2. 停止:
    • ID
    • loadId

一個負載可能有多個停止但停止有一個負載。 負載至少有兩個停靠原點和目的地。

我已經創建了模型

class LoadsModel extends Model
{
    protected $table = 'loads';
    public function stops(){
    return $this->hasMany('App\Stops');
    }
}

class Stops extends Model
{
   protected $table = 'stops';
   public function loads(){
    return $this->belongsTo('App\LoadsModel');
   }
}

我正在使用模型將模型傳遞到視圖中。

  public function index()
  {
      $loads = LoadsModel::orderBy('loadId')->get();
      return view('tender.available')->with(['loads'=>$loads]);
  }

我希望根據表格標題在刀片中顯示結果,其中Origin城市是停靠點的原始城市,其id與裝載表中的originstopId相同,而停靠點的目標城市,其id是裝載中的destStopId表。 我想顯示一個負載的停止計數。 像這樣的東西。

<table class="table">
    <tr>
       <th>Origin City</th>
       <th>Origin State</th>
       <th>Destination City</th>
       <th>Destination State</th>
       <th>Load Id</th>
       <th>Stops</th>
    </tr>
</table>

您應該使用foreach循環來訪問每個加載的每個屬性:

@foreach($loads as $load)
 <tr>
     <th>{{$load->id}}</th>
              .
              .
              .
     <th>{{$load->anyAttributeYouWant}}</th>

     @foreach($load->stops as $stop)
         <th>{{$stop->id}}</th>
         <th>{{$stop->city}}</th>
         <th>{{$stop->state}}</th>
     @endforeach
 </tr>
@endforeach

我也在你的停止關系中做了一個foreach,所以你可以顯示停止的所有屬性。

您可以使用withCount 方法計算負載的停靠點:

public function index()
{
    $loads = LoadsModel::orderBy('loadId')->withCount('stops')->get();
    return view('tender.available')->with(['loads'=>$loads]);
}

您可以在視圖中訪問計數,如下所示:

{{$load->stops_count}}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM