두 클래스가 있습니다 : Artist
및 Instrument
입니다. 각각 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 개 질문이
제 생각에는 0123을 출력 할 수 있습니다.같은 :
{{ $artist->firstname }}
내가 같은
$instruments
을 반복 할 수 있습니다@foreach ($instruments as $instrument) <h2>{{ $instrument->name }}</h2> @endforeach
있지만
$artist
을 반복 할 수 있습니다 (I가 알고있는 단 하나의 - 참조 # 2) 각$artist
반복 처리를위한 이상 그들의$instruments
?내 컨트롤러에서 모든 아티스트와 # 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()
이 정의되지 않았다고 말하는 오류가 발생한다.
ArtistController.php
$artist = Artist::find($artist_id);
$instruments = $artist->instruments()->get();
return \View::make('artists')->with('artists', $artists)->with('instruments', $instruments);
을
내 모델 관계에 뭔가 이상하다고 가정하고 있습니다. 나는 또한 Artist.php과 hasMany
으로 내 관계를 정의하려고 시도했다. (나는 "각 아티스트 hasMany Instruments"라고 말하는 것이 더 합리적이라고 생각한다. 그러나 이것은 artists_instruments
이라는 테이블을 기대하고 있기 때문에 오류가 발생하고 또한 시도하고있다. 해당 테이블에없는 열 (예 : name
)을 검색 할 수 있습니다.
시도하여 -> ('FIRSTNAME')를 얻는다. (나는 'id', 'firstname'))를 얻는다. – Patrick