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 求糕手!用matlab求解目标规划模型🙏
  • ¥15 画出的分类图不对,求解答一下
  • ¥20 springboot和springcloud版本问题
  • ¥15 ps2手柄控制树莓派小车
  • ¥30 C#:vsto powerpoint的外接程序
  • ¥30 stata将do文件代码转化为ado文件
  • ¥15 两个同维数组相比,不同位置、出现重复比无意义,而不同位置、不出现重复比,则有意义。把有意义的两个数组放入新的集合MK中。
  • ¥15 可以远程电脑安装nvm
  • ¥15 写一个可直接调用的函数,将32位有符号数转成另一个无符号的数
  • ¥15 CMAKE+VS2019+QT5.15.2组合进行二次编译