2014-02-12 1 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 


나는 성공적 그래서 같은 하나 예술가 및 관련 장비 검색 할 수 있어요 :

    : 나는 3 개 질문이

    ArtistController.php

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

  1. 제 생각에는 0123을 출력 할 수 있습니다.같은 :

    {{ $artist->firstname }} 
    

    내가 같은 $instruments을 반복 할 수 있습니다

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

    있지만 $artist을 반복 할 수 있습니다 (I가 알고있는 단 하나의 - 참조 # 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 Instruments"라고 말하는 것이 더 합리적이라고 생각한다. 그러나 이것은 artists_instruments이라는 테이블을 기대하고 있기 때문에 오류가 발생하고 또한 시도하고있다. 해당 테이블에없는 열 (예 : name)을 검색 할 수 있습니다.

+1

시도하여 -> ('FIRSTNAME')를 얻는다. (나는 '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 - 그건 분명히 별개의 질문입니다. –