Laravel 4.1:检索所有morphedBy关系的正确方法? [英] Laravel 4.1: proper way to retrieve all morphedBy relations?

查看:296
本文介绍了Laravel 4.1:检索所有morphedBy关系的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只需迁移到4.1,即可利用此强大功能. 检索单个'morphedByXxxx'关系时,一切似乎都正常工作,但是,当尝试检索属于 的所有模型时,我得到一个错误或没有结果.

Just migrated to 4.1 to take advantage of this powerful feature. everything seems to work correctly when retrieving individual 'morphedByXxxx' relations, however when trying to retrieve all models that a particular tag belongs to -- i get an error or no results.

$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 loooks like this:

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

}

发布"和视频"模型如下所示:

And the Post and Video models look like this:

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

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

}

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

I am able to add/remove Tags to Posts and Videos as well as retrieve the related Posts, and Videos for any Tag -- however -- what is the proper way to retrieve all Models having the Tag name 'awesome'?

推荐答案

能够弄清楚了,很想听听对此实施方案的评论.

Was able to figure it out, would love to hear comments on this implementation.

在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();

这篇关于Laravel 4.1:检索所有morphedBy关系的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆