php - Laravel Eloquent : Inverse of Many To Many (Polymorphic)

标签 php laravel eloquent laravel-8

从 Laravel 官方文档复制的示例:

例如,Post 模型和 Video 模型可以共享与 Tag 模型的多态关系。在这种情况下使用多对多多态关系将允许您的应用程序拥有一个可能与帖子或视频关联的唯一标签表。首先,让我们检查一下构建此关系所需的表结构:

posts
id - integer
name - string

videos
id - integer
name - string

tags
id - integer
name - string

taggables
tag_id - integer
taggable_id - integer
taggable_type - string

从标签对象中,我想获取该标签所属的所有视频和帖子(在 morphOne 和 morphMany 的情况下,我可以通过 morphTo() 方法来做到这一点)

Laravel 说,我需要在标签模型中定义视频和帖子方法才能定义逆,但我想要一个像 taggables 这样的关系,它将返回受尊重的父级(无论是帖子还是视频)

enter image description here

Reference

我需要类似可成像的东西(但它是一对一的多态性,我需要多对多的这种东西) enter image description here

最佳答案

您可以在数据透视模型中使用 MorphOne/MorphMany

https://laravel.com/docs/8.x/eloquent-relationships#defining-custom-intermediate-table-models

class Video extends Model
{
    public function tags()
    {
        return $this->morphToMany(Tag::class, 'taggable')->using(Taggable::class);
    }

    public function taggables()
    {
        return $this->morphMany(Taggable::class, 'taggable');
    }
}
class Post extends Model
{
    public function tags()
    {
        return $this->morphToMany(Tag::class, 'taggable')->using(Taggable::class);
    }

    public function taggables()
    {
        return $this->morphMany(Taggable::class, 'taggable');
    }
}
class Tag extends Model
{
    public function posts()
    {
        return $this->morphedByMany(Post::class, 'taggable')->using(Taggable::class);
    }

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

    public function taggables()
    {
        return $this->hasMany(Taggable::class/*, 'tag_id'*/)
    }
}
use Illuminate\Database\Eloquent\Relations\MorphPivot;

class Taggable extends MorphPivot
{
    public $incrementing = false; // this is the default value. Change if you need to.
    public $guarded = [];         // this is the default value. Change if you need to.
    protected $table = 'taggables';

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

    public function tag()
    {
        return $this->belongsTo(Tag::class/*, 'tag_id'*/);
    }
}

关于php - Laravel Eloquent : Inverse of Many To Many (Polymorphic),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70957090/

相关文章:

javascript - 未捕获的 TypeError : Cannot set property 'app' of undefined Vue. js

php - 仍然显示相同的错误: cURL error 60: SSL certificate problem: unable to get local issuer certificate

php - 如何根据数据库下拉列表的 mysql 计数来限制或停止表单提交?

php - 在symfony2中引用静态模板

javascript - 嵌入来自用户提交的 URL 的内容

php - 如何在 Laravel 中创建和使用自定义的每日日志文件?

php - MySQL UPDATE 列的值并用旧值添加新值

mysql - 如何在 "User::with"查询中使用 eloquent 获取 Laravel 中的某些列?

php - 你可以在数据库 Laravel 4 中插入声明的变量吗

php - Laravel Eloquent 在播种期间无人看守