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

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)