簡體   English   中英

Laravel Eloquent:多對多的逆(多態)

[英]Laravel Eloquent: Inverse of Many To Many (Polymorphic)

從官方 Laravel 文檔復制的示例:

例如,帖子 model 和視頻 model 可以與標簽 model 共享多態關系。 在這種情況下使用多對多多態關系將允許您的應用程序擁有一個可能與帖子或視頻相關聯的唯一標簽表。 首先,讓我們檢查建立這種關系所需的表結構:

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

從標簽 object 我想獲取該標簽所屬的所有視頻和帖子(在 morphOne 和 morphMany 的情況下,我可以通過 morphTo() 方法做到這一點)

Laravel 說,我需要在標簽 model 中定義視頻和發布方法以定義逆向但我想要一個像可標記的關系,它將返回受人尊敬的父級(無論是帖子還是視頻)

在此處輸入圖像描述

參考

我需要類似 imageable 的東西(但它是一對一的多態,我需要多對多的這種東西) 在此處輸入圖像描述

您可以在 pivot model 中使用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'*/);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM