1

我尝试在 Laravel 5.1 中显示带有刀片的嵌套数组,但我不能这样做:

控制器:

public function track($id){
  $tracks = track::with('trials.samples')->where('trials_id',$id)->get();

  //return $tracks;
  return view('Tracks.index',compact('tracks'));
}

Traks.index:

{{ $track['samples']['variety'] }} 

返回 $tracks 返回:

[{
    "id": 1,
    "trials_id": 1,
    "date": "2015-12-16",
    "comments": "\u0646\u062a\u06cc\u062c\u0647 \u062e\u0627\u0635\u06cc \u0646\u062f\u0627\u0634\u062a\u0647 !",
    "created_at": "-0001-11-30 00:00:00",
    "updated_at": "-0001-11-30 00:00:00",
    "trials": {
        "id": 1,
        "persons_id": 1,
        "samples_id": 1,
        "amount": "125000",
        "date": "2015-12-09",
        "comments": "",
        "code": "5CEPY",
        "created_at": "2015-12-08 06:46:58",
        "updated_at": "2015-12-08 06:46:58",
        "samples": {
            "id": 1,
            "variety": "keyhan",
            "supplier_id": 1,
            "lot_number": "2550",
            "date": "2015-12-11",
            "amount": 125000,
            "unit_id": 1,
            "technical_fact": "\u0641\u0646\u06cc",
            "comments": "1",
            "file_address": "",
            "category_id": 1,
            "created_at": "2015-12-08 06:46:34",
            "updated_at": "2015-12-08 06:46:34"
        }
    }
}]

我也试过这段代码,但没有显示:

{{ $track['trials.samples']['variety'] }} 
{{ $track->samples['variety'] }} 
4

1 回答 1

1

首先,我从来没有compact()将任何东西返回给视图,所以我不熟悉它的用法。

但是,您可以使用with()将内容返回到视图,因此如果您将该行更改为:

return view('Tracks.index')->with(["tracks" => $tracks]);

然后,您可以使用@foreach循环在刀片中显示它们,或者使用$tracks[0].... 例如:

@foreach($tracks AS $track)
  {{ $track->comments }}
  @foreach($track->trials AS $trial)
    {{ $trial->code }}
    @foreach($trial->samples AS $sample)
      {{ $sample->variety }}
    @endforeach
  @endforeach
@endforeach

请注意,这取决于您的关系是如何在Track,TrialSample模型中设置的。例如:

public function trials(){
  return $this->hasMany("App\Trial")->get();
  // vs 
  return $this->hasOne("App\Trial")->first();
}

如果是->get(),您必须使用@foreach语法来访问它,但如果您只期望一个结果,您可以简单地使用:

{{ $track->trials->samples->variety }}

如果您需要更多信息,请查看 Laravel 的文档:Blade Documentation和Eloquent Collections

于 2015-12-08T20:10:29.223 回答