2014-02-12 89 views
2

我有兩個類:ArtistInstrument。每個Artist可以播放一個或多個Instrument。並且每個Instrument可以被分配給一個或多個Artist。所以,我已經設置了以下類:Laravel 4和Eloquent:檢索所有記錄和所有相關記錄

Artist.php

public function instruments() { 
    return $this->belongsToMany('App\Models\Instrument'); 
} 

Instrument.php

public function artists() { 
    return $this->belongsToMany('\App\Models\Artist'); 
} 


然後我有三個數據庫表:

artists: id, firstname, lastname, (timestamps) 
instruments: id, name 
artist_instrument: id, artist_id, instrument_id 


我能夠成功地檢索一個藝術家和他們的相關文書,像這樣:

ArtistController.php

$artist = Artist::find($artist_id); 
$instruments = $artist->instruments()->get(); 
return \View::make('artists')->with('artists', $artists)->with('instruments', $instruments); 

我有3個問題:

  1. 在我看來,我可以輸出$artist,如:

    {{ $artist->firstname }} 
    

    ,我可以通過$instruments像迭代:

    @foreach ($instruments as $instrument) 
        <h2>{{ $instrument->name }}</h2> 
    @endforeach 
    

    但有可能遍歷$artist(我知道,只有一個 - 見#2),併爲每個$artist疊代他們的$instruments

  2. 在我的控制,我怎麼會得到所有藝術家併爲每個通過它們在我看來迭代的最終目標是那些其相關文書的#1所描述的。

  3. 是否有可能只檢索上述ArtistController.php示例中的特定列?我試過這個:

    $artist = Artist::where('id', $artist_id)->get('firstname'); 
    $instruments = $artist->instruments()->get(); 
    return \View::make('artists')->with('artists', $artists)->with('instruments', $instruments); 
    

    但我得到一個錯誤,說Collection::instruments()是未定義的。

我假設我的模型關係中有些東西不正確。我也試着定義我的關係在Artist.phphasMany(我認爲它更有意義,說:「每一位藝術家的hasMany儀器」,但給我一個錯誤,因爲它期待一個表名爲artists_instruments,它也試圖檢索該表中不存在的列(如name

+1

嘗試,包括在你的藝術家的關係關鍵的 - >獲取( '名字')。 (我假設它會是這樣的'id': - > get('id','firstname')) – Patrick

回答

8

您的模型關係沒問題。

控制器:

$artists = Artist::with('instruments')->get(); 

return \View::make('artists')->withArtists($artists); 

查看:

@foreach ($artists as $artist) 

    <h1>{{ $artist->firstname }}</h1> 

    @foreach ($artist->instruments as $instrument) 

     <h2>{{ $instrument->name }}</h2> 

    @endforeach 

@endforeach 
+2

我只是偶然發現了你發佈的答案,這正是我所做的。謝謝! – tptcat

+0

還有一件事(如果有意義,我可以將其作爲單獨的問題發佈)如果我不想檢索所有這些列,我將如何指定要檢索的列?我試過在不同的地方使用'select()',但似乎沒有任何工作。 – tptcat

+0

@tptcat - 這絕對應該是一個單獨的問題。 –

相關問題