在Laravel Eloquent中检索所有morphBy​​Many关系 [英] Retrieving all morphedByMany relations in Laravel Eloquent

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

问题描述

在Laravel文档中,有以下示例检索 morphedByMany 关系,它们是多对多多态关系。

In the Laravel documentation, there is the following example for retrieving morphedByMany relations, which are many-to-many polymorphic relations.

Laravel多对多多态关系文档

namespace App;

use Illuminate\Database\Eloquent\Model;

class Tag extends Model
{
    /**
     * Get all of the posts that are assigned this tag.
    */
    public function posts()
    {
        return $this->morphedByMany('App\Post', 'taggable');
    }

    /**
     * Get all of the videos that are assigned this tag.
     */
    public function videos()
    {
        return $this->morphedByMany('App\Video', 'taggable');
    }
}

我将如何获取所有<$ c的列表在一个查询/集合中,$ c>变形的关系,例如,帖子视频 ,然后再添加张照片(或其他任何东西),也是吗?

How would I get a list of all morphed relations in one query / collection, for instance, posts and videos, and then if I later added photos (or anything), that too?

推荐答案

我在这里使用一个技巧:

I use a trick here:

为连接表<$ c $创建模型 Taggable c>可标记,并向 Tag 模型添加 hasMany 关系。

Create a Model Taggable for your connection table taggable and add a hasMany relation to the Tag model.

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

在您的可标记中模型创建 morphedTo 关系。

Within your Taggable model create a morphedTo relation.

public function taggables()
{
    return $this->morphTo();
}

现在,您可以通过调用以下命令获取所有正在使用该标签的模型:

Now you can get all models witch are using the tag by calling:

$tagged = Tag::with('related.taggables');

这篇关于在Laravel Eloquent中检索所有morphBy​​Many关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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