dtmjl4427
2019-04-05 20:40
浏览 74
已采纳

在laravel模型中使用关系如何获取刀片文件中的数据?

I am querying data from database with two tables.

  1. Loads:
    • LoadId
    • OriginStopId
    • DestStopId
  2. Stops:
    • id
    • City
    • State
    • loadId

A Load could have multiple stops but a stop has one load. A load has minimum two stops the origin and the destination.

I have created the models as

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

and

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

I am using the model to pass the model into the view.

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

I want to show the result in a blade as according to the table headers where the Origin city is the origin city of the stop whose id is the same as the originstopId in loads table and Destination city of the stop whose id is the destStopId in loads table. I want to show the counts of the stops of a load. Something like this .

<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>
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duangejian6657 2019-04-05 21:30
    已采纳

    You should use a foreach loop to access every attribute from each load:

    @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
    
    

    I've made a foreach in your stops relation too, so you can show all the atributes from the stops.

    You could count the stops from a load using the withCount method:

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

    You can access the count in your view like this:

    {{$load->stops_count}}
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题