我有两节课:Artist
and Instrument
. Each Artist
可以玩一个或多个Instrument
s。还有每一个Instrument
可以分配给一个或多个Artist
s。因此,我设置了以下课程:
艺术家.php
public function instruments() {
return $this->belongsToMany('App\Models\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
like:
{{ $artist->firstname }}
我可以迭代$instruments
like:
@foreach ($instruments as $instrument)
<h2>{{ $instrument->name }}</h2>
@endforeach
但是否可以迭代$artist
(我知道只有一个 - 请参阅#2)并且对于每个$artist
迭代他们的$instruments
?
在我的控制器中,我将如何得到all艺术家及其相关乐器,在我看来,最终目标是迭代它们,如#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()
未定义。
我假设我的模型关系中有一些不对劲的地方。我也尝试过定义我的关系艺术家.php with a hasMany
(我认为说“每个艺术家都有许多乐器”更有意义,但这给了我一个错误,因为它需要一个名为artists_instruments
并且它还尝试检索该表中不存在的列(例如name
).
你的模特关系很好。
控制器:
$artists = Artist::with('instruments')->get();
return \View::make('artists')->withArtists($artists);
View:
@foreach ($artists as $artist)
<h1>{{ $artist->firstname }}</h1>
@foreach ($artist->instruments as $instrument)
<h2>{{ $instrument->name }}</h2>
@endforeach
@endforeach
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)