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}}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 全志H618ROM新增分区
  • ¥20 jupyter保存图像功能的实现
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示
  • ¥15 NAO机器人的录音程序保存问题
  • ¥15 C#读写EXCEL文件,不同编译
  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况