함께

2014-06-15 2 views
2

From the Laravel documentation이 개 다형성 관계 결과를 얻을 -이 대다 다형성 관계가있는 경우 :함께

class Tag extends Eloquent { 

    public function posts() 
    { 
     return $this->morphedByMany('Post', 'taggable'); 
    } 

    public function videos() 
    { 
     return $this->morphedByMany('Video', 'taggable'); 
    } 

} 

그래서 나는이 작업을 수행 할 수 있습니다

$tag = Tag::find(1); 
$posts = $tag->posts; 
$videos = $tag->videos; 

을 나는 모든 태그를 얻을 수있는 방법 관계를 하나의 결과로? 일대 다 다형성 관계 즉, 당신은이 작업을 수행 :

$tag = Tag::find(1); 
$taggable = $tag->taggable; 

하지만 나던은 다 대다 관계에서 나를 위해 작동하는 것 -이 SQL 오류 얻을 :

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'tag_groups.' in 'where clause' (SQL: select * from tag_groups where tag_groups .`` is null limit 1)

+0

당신이 할 무엇을 기대할 결과를 사용하고 계십니까? Eloquent Collection은 키 중복을 가질 수 있기 때문에 갈 길이 아닙니다. –

답변

4

당신은 결과를 직접 병합해야합니다 :

$taggable = $tag->posts->toBase()->merge($tag->videos); 

Illuminate\Support\Collection의 인스턴스를 반환합니다.

이 문맥에서 Eloquent 컬렉션은 의미가 없습니다.

3

당신은 하나 개의 결과의 모든 관계를 얻을 수 있지만, 당신은 그 (것)들에게이 같은 모든 열망 사용하여 뭔가로드 할 수 있습니다 : 당신은 같은 것을 사용하여 하나에 액세스 할 수 있도록

다음
$tag = Tag::with(['posts', 'videos'])->find(1); 
$relations = $tag->getRelations(); 

$tag->getRelations()가로드 관계의 배열을 반환됩니다 이 : 당신이 그들을 병합 할 수 있습니다

$posts = $relations['posts']; // Collection of Post models 
$videos = $relations['videos']; // Collection of Video models 

좋아 :

$allRelations = array_merge($posts->toArray(), $videos->toArray()); 

또는 (언급 Joseph Silber로) Illuminate\Support\Collectionmerge 방법

$allRelations = $relations['posts']->toBase()->merge($relations['videos']);