2013-05-29 50 views
0

我有以下途徑:模型關係和路線得到模型ID

Route::get('notes/main', function(){ 

     $destinations = Destination::where('show', '=','1')->get(); 
     $notes = Destination::find($destination->id)->notes()->get(); 
     return View::make('notes.main') 
     ->with('destinations', $destinations); 

}); 

//關係模型:

<?php 
class Destination extends Eloquent { 
    public function notes() 
    { 
    return $this->has_many('Note'); 
    } 
} 

<?php 
class Note extends Eloquent 

{ 
     public function destination() 
     { 
      return $this->belongs_to('Destination'); 
     } 

} 

//查看:

@foreach($destinations as $destination) 

{{ $destination->name}}<br> 
{ $notes->destination->text }} // this isn't echoed 
@endforeach 

什麼是正確的方式來過濾這個並定義$ destination-> id

謝謝

我將如何篩選循環內if語句中的註釋? @if(isset($注意 - >稱號)!= 'shorttext')

  @else 
      <p> {{ $note->text }} </p> 
      @endif 
      @endforeach 

回答

-1

OK 這個工作在末端 功能isset和空沒有工作,奇道:

@if ($note->title == 'shorttext') 
0

在你的路線,你不發送$註解變量視圖。

我會怎麼做:

$destinations = Destination::where('show', '=','1')->get(); 
    $destinations->notes = Destination::find($destination->id)->notes()->get(); 

然後在視圖:

@foreach($destinations as $destination) 
    {{ $destination->name}}<br> 
    {{ $destination->notes->text }} 
@endforeach 
+0

我得到:未定義的變量:目的地 – dflow

1

您使用$ destination-> ID在你的路線,但它似乎還沒有定義。問題是,你想用你的代碼實現什麼? 有了:

$destinations = Destination::where('show', '=','1')->get(); 
$notes = Destination::find($destination->id)->notes()->get(); 

你得到只有一個特定目的地的注意事項(到目前爲止,沒有定義$目的地,您可以使用目標::所有() - >第()獲得第一,或。 Destination :: find(id),ID用您需要的目標的主鍵值替換)。

但我想你不想那樣。從您的輸出中,您似乎希望在每個目標位置輸出相應的註釋,並在每個目標位置下方輸出。

控制器:

//gets all the destinations 
$destinations = Destination::where('show', '=','1')->get(); 
return View::make('notes.main') 
    ->with('destinations', $destinations); 

查看:

@foreach($destinations as $destination) 
    {{ $destination->name}}<br> 
    @foreach($destination->notes as $note) 
    {{ $note->text }} <br> 
    @endforeach 
    <hr> 
@endforeach 

沒有測試這一點,但這樣一來您的視圖會顯示您的所有目的地,併爲每個目的地的所有注意事項。最後一部分

+0

感謝Matthias,唯一的: – dflow

+0

您的評論似乎被削減,但我看到我在輸出中犯了一個錯誤。它不應該是$ destination-> notes-> text,而是$ note-> text。我會相應地編輯它 –

0

因此首先要問一個問題,我給你一個正確的答案。 您將我的答案標記爲已接受,但後來編輯您的初始問題以添加另一個問題(您應該爲其創建一個新線程)。 然後你創建自己的答案,只回答你最初的問題的一部分,並將其標記爲好的解決方案?

我可以告訴你爲什麼你的isset和empty不起作用,但爲什麼我應該如果你不重視我的幫助呢?