Laravel 4.1:检索所有morphedBy关系的正确方法?

时间:2013-09-07 02:27:51

标签: laravel many-to-many laravel-4 polymorphism

刚迁移到4.1以利用这一强大功能。 在检索单个'morphedByXxxx'关系时,一切似乎都能正常工作,但是当尝试检索特定标记所属的所有模型时 - 我收到错误或没有结果。

$tag = Tag::find(45); //Tag model name = 'awesome'

//returns an Illuminate\Database\Eloquent\Collection of zero length
$tag->taggable; 

//returns Illuminate\Database\Eloquent\Relations\MorphToMany Builder class
$tag->taggable();

//returns a populated Collection of Video models
$tag->videos()->get();

//returns a populated Collection of Post models
$tag->posts()->get();

My Tag Model类就像这样:

class Tag extends Eloquent
{
    protected $table = 'tags';
    public $timestamps = true;

    public function taggable()
    {
        //none of these seem to function as expected,
        //both return an instance of MorphToMany

        //return $this->morphedByMany('Tag', 'taggable');
        return $this->morphToMany('Tag', 'taggable');

        //this throws an error about missing argument 1
        //return $this->morphToMany();
    }

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


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

}

Post和Video模型如下所示:

class Post extends Eloquent
{
    protected $table = 'posts';
    public $timestamps = true;

    public function tags()
    {
        return $this->morphToMany('Tag', 'taggable');
    }

}

我能够为帖子和视频添加/删除标签,以及检索任何标签的相关帖子和视频 - 但是 - 检索所有模型的正确方法是什么< em> 标签名称'awesome'?

2 个答案:

答案 0 :(得分:6)

能够弄明白,很想听听有关此实施的评论。

Tag.php中的

public function taggable()
{
    return $this->morphToMany('Tag', 'taggable', 'taggables', 'tag_id')->orWhereRaw('taggables.taggable_type IS NOT NULL');
}

调用代码:

$allItemsHavingThisTag = $tag->taggable()
                ->with('videos')
                ->with('posts')
                ->get();

答案 1 :(得分:0)

我刚刚在Laravel 5.2上使用过它(不确定它是否是一个好的策略):

标签型号:

public function related()
{
    return $this->hasMany(Taggable::class, 'tag_id');
}

Taggable型号:

public function model()
{
    return $this->belongsTo( $this->taggable_type, 'taggable_id');
}

要检索所有反向关系(附加到请求标记的所有实体):

@foreach ($tag->related as $related)
    {{ $related->model }}
@endforeach

......遗憾的是,这种技术并不能提供令人满意的负载功能,而且感觉就像黑客一样。至少它可以很容易地检查相关的模型类并显示所需的模型属性,而不必担心在正确的模型上寻找正确的属性。

我在this other thread发布了一个类似的问题,因为我正在寻找事先未知的关系。