2014-10-06 42 views
0

非常簡單的問題:Laravel eloquent docs指定morphTo函數定義多態,反一對一或多關係。無論如何(laravel叉可能?)創建一個多態的,非反向的一對一或多個關係,而不用自己做,並在Laravel的雄辯關係代碼中潛水?Laravel直變體關係

需要明確的是:我想要做的事,如:

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(或你們的關係從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功能,您可以找到差異here