Laravel直接变形关系

时间:2014-10-06 22:56:25

标签: laravel eloquent

非常简单的问题:Laravel eloquent docs指定morphTo函数定义多态,反一对一或多种关系。无论如何(laravel forks可能?)创建一个多态的,非逆的一对一或多种关系,而不是自己动手并在Laravel的Eloquent关系代码中潜水?

要明确:我想做类似的事情:

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 个答案:

答案 0 :(得分:1)

实际上,我通过挖掘Laravel Eloquent课程并自己编写代码找到了解决方案。

这样做的两种方式,要么创建新的关系,要么只是修补' MorphTo关系允许变形的实例拥有多个父项。

无论哪种方式,解决方案只需通过替换MorphTo(或从MorphTo复制的关系)matchToMorphParents函数

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']));
        }
    }
}

你可以找到差异here