在 Laravel Eloquent 中检索所有 morphedByMany 关系

2021-12-26 00:00:00 polymorphism php laravel eloquent

在 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 IlluminateDatabaseEloquentModel;

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

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

我如何获得一个查询/集合中所有 morphed 关系的列表,例如 postsvideos,然后如果我后来添加了照片(或任何东西),那也是?

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:

为您的连接表 taggable 创建一个模型 Taggable 并添加一个 hasMany 关系到 Tag 模型.

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

在你的 Taggable 模型中创建一个 morphedTo 关系.

Within your Taggable model create a morphedTo relation.

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

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

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

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

相关文章