在 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
关系的列表,例如 posts
和 videos
,然后如果我后来添加了照片
(或任何东西),那也是?
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');
这篇关于在 Laravel Eloquent 中检索所有 morphedByMany 关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!