2014-10-06 3 views
0

매우 간단한 질문 : Laravel eloquent docs morphTo 함수가 다형성, 역 일대일 또는 많은 관계를 정의하도록 지정합니다. 어쨌든 (Laravel 포크 어쩌면?) 다형성, 비역 일대일 또는 많은 관계를 만들 수 있습니까? Laravel의 Eloquent relationships 코드에서 직접 해보지 않고 다이빙을하지 않습니까?Laravel straight morphTo 관계

것은 명확하게하려면 : 나는 같은 것을하고 싶지 : 다음

class Answer extends Eloquent { 
    protected $fillable = array('answer_id', 'answer_type'); 

    public function answers() { 
     return $this->straightMorphTo('answer_id', 'answer_type', 'id'); 
    } 
} 

class AnswerFirst extends Eloquent { 
    protected $fillable = array('id', 'text'); 

    public function answers() { 
     return $this->belongsTo('Answer'); 
    } 
} 

class AnswerSecond extends Eloquent { 
    protected $fillable = array('id', 'number'); 

    public function answers() { 
     return $this->belongsTo('Answer'); 
    } 
} 

// 
// Answer 
// ------------------------------------ 
// answer_id  | answer_type  | 
// ------------------------------------ 
// 1    | AnswerFirst  | 
// 2    | AnswerSecond  | 
// ------------------------------------ 
// 
// AnswerFirst 
// ------------------------------------ 
// id   | text    | 
// ------------------------------------ 
// 1    | 1rst part   | 
// 1    | 2nd part   | 
// ------------------------------------ 
// 
// AnswerSecond 
// ------------------------------------ 
// id   | number    | 
// ------------------------------------ 
// 2    | 1     | 
// 2    | 2     | 
// ------------------------------------ 
// 

그리고을, 답변 :로 ('답') -> 찾기 (2) 사실

{ 
    id:'2', 
    answer_type:'AnswerSecond', 
    answers: [ 
     {id:'2',number:'1'}, 
     {id:'2',number:'2'}, 
    ] 
} 

답변

1

를 반환해야 Laravel Eloquent 클래스를 파고 직접 코딩함으로써 해결책을 찾았습니다.

두 가지 방법으로, 새로운 관계를 만들거나 MorphTo 관계에 '패치'하여 변형 된 인스턴스가 여러 부모를 가질 수있게합니다.

어느 쪽이든이 솔루션은 (또는 MorphTo에서 복사하여 관련)

protected function matchToMorphParents($type, Collection $results) 
{ 
    $resultsMap = array(); 
    foreach ($results as $result) 
    { 
     if (isset($this->dictionary[$type][$result->getKey()])) 
     { 
      foreach ($this->dictionary[$type][$result->getKey()] as $model) 
      { 
       $resultsMap[$model->{$this->foreignKey}]['model'] = $model; 
       if (!array_key_exists('results', $resultsMap[$model->{$this->foreignKey}])) { 
        $resultsMap[$model->{$this->foreignKey}]['results'] = array(); 
       } 
       array_push($resultsMap[$model->{$this->foreignKey}]['results'], $result); 
      } 
     } 
    } 
    foreach ($resultsMap as $map) 
    { 
     if (sizeof($map['results']) === 1) { 
      $map['model']->setRelation($this->relation, $map['results'][0]); 
     } else { 
      $map['model']->setRelation($this->relation, new Collection($map['results'])); 
     } 
    } 
} 

에 의해 matchToMorphParents 기능 당신은 diff를 찾을 수 있습니다 단지 MorphTo을 대체하여 제공 here