从 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 这样的关系,它将返回受尊重的父级(无论是帖子还是视频)
最佳答案
您可以在数据透视模型中使用 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/