我有两个类: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