我有兩個類:Artist
和Instrument
。每個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個問題:
在我看來,我可以輸出
$artist
,如:{{ $artist->firstname }}
,我可以通過
$instruments
像迭代:@foreach ($instruments as $instrument) <h2>{{ $instrument->name }}</h2> @endforeach
但有可能遍歷
$artist
(我知道,只有一個 - 見#2),併爲每個$artist
疊代他們的$instruments
?在我的控制,我怎麼會得到所有藝術家併爲每個通過它們在我看來迭代的最終目標是那些其相關文書的#1所描述的。
是否有可能只檢索上述
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.php與hasMany
(我認爲它更有意義,說:「每一位藝術家的hasMany儀器」,但給我一個錯誤,因爲它期待一個表名爲artists_instruments
,它也試圖檢索該表中不存在的列(如name
)
嘗試,包括在你的藝術家的關係關鍵的 - >獲取( '名字')。 (我假設它會是這樣的'id': - > get('id','firstname')) – Patrick