【发布时间】:2014-03-11 04:42:44
【问题描述】:
我有两个班级:Artist 和 Instrument。每个Artist 可以播放一个或多个Instruments。并且每个Instrument 可以分配给一个或多个Artists。所以,我设置了以下类:
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
我能够成功地检索到 one 艺术家及其相关乐器,如下所示:
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 中所述。 p>
-
是否可以只检索上述
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()未定义。
我假设我的模特关系中有什么不对劲的地方。我还尝试用hasMany 定义我在 Artist.php 中的关系(我认为说“每个艺术家都有很多乐器”更有意义,但这给了我一个错误,因为它期待一个名为artists_instruments 的表,它还试图检索该表中不存在的列(如name)。
【问题讨论】:
-
尝试在 ->get('firstname') 中包含 Artist 的关系密钥。 (我假设它会是这样的 'id':->get('id', 'firstname'))
标签: orm laravel foreign-key-relationship eloquent