Laravel 4和Eloquent:检索所有记录和所有相关记录

tpt*_*cat 2 orm foreign-key-relationship laravel eloquent

我有两个班:ArtistInstrument.每个人都Artist可以玩一个或多个Instrument.并且每个Instrument都可以分配给一个或多个Artists.所以,我已经设置了以下类:

Artist.php

public function instruments() {
    return $this->belongsToMany('App\Models\Instrument');
}
Run Code Online (Sandbox Code Playgroud)

Instrument.php

public function artists() {
    return $this->belongsToMany('\App\Models\Artist');
}
Run Code Online (Sandbox Code Playgroud)


然后我有三个数据库表:

artists: id, firstname, lastname, (timestamps)
instruments: id, name
artist_instrument: id, artist_id, instrument_id
Run Code Online (Sandbox Code Playgroud)


我能够成功找回一位艺术家及其相关乐器,如下所示:

ArtistController.php

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

我有3个问题:

  1. 在我看来,我可以输出$artist像:

    {{ $artist->firstname }}
    
    Run Code Online (Sandbox Code Playgroud)

    我可以迭代$instruments:

    @foreach ($instruments as $instrument)
        <h2>{{ $instrument->name }}</h2>
    @endforeach
    
    Run Code Online (Sandbox Code Playgroud)

    但是有可能迭代$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);
    
    Run Code Online (Sandbox Code Playgroud)

    但我得到一个错误,说Collection::instruments()是未定义的.

我假设我的模型关系中存在一些不正确的东西.我也试着定义我的关系Artist.phphasMany(我认为它更有意义,说:"每一位艺术家的hasMany仪器",但给我一个错误,因为它是期待一个表命名artists_instruments,它也试图找回那列不会存在于该表中(如name).

Jos*_*ber 8

你的模特关系很好.

控制器:

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

return \View::make('artists')->withArtists($artists);
Run Code Online (Sandbox Code Playgroud)

视图:

@foreach ($artists as $artist)

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

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

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

    @endforeach

@endforeach
Run Code Online (Sandbox Code Playgroud)

  • 我刚发布的时候偶然发现了答案,这正是我所做的.谢谢! (2认同)