2014-02-12 67 views
2

我有两个类:ArtistInstrument。每个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个问题:

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

    {{ $artist->firstname }} 
    

    ,我可以通过$instruments像迭代:

    @foreach ($instruments as $instrument) 
        <h2>{{ $instrument->name }}</h2> 
    @endforeach 
    

    但有可能遍历$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); 
    

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

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

+1

尝试,包括在你的艺术家的关系关键的 - >获取( '名字')。 (我假设它会是这样的'id': - > get('id','firstname')) – Patrick

回答

8

您的模型关系没问题。

控制器:

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

return \View::make('artists')->withArtists($artists); 

查看:

@foreach ($artists as $artist) 

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

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

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

    @endforeach 

@endforeach 
+2

我只是偶然发现了你发布的答案,这正是我所做的。谢谢! – tptcat

+0

还有一件事(如果有意义,我可以将其作为单独的问题发布)如果我不想检索所有这些列,我将如何指定要检索的列?我试过在不同的地方使用'select()',但似乎没有任何工作。 – tptcat

+0

@tptcat - 这绝对应该是一个单独的问题。 –

相关问题