Laravel 8 - 动态定义关系
Laravel 8 - define relationships dynamically
所以我正在尝试构建功能以允许用户对不同类型的数据发表评论。博客文章、视频、图像、文档、评论(回复)等。因此,每一个都需要定义与 Comments 模型的关系。所以基本上
public function comments()
{
return $this->morphMany(Comment::class, 'commentable')->whereNull('parent_id');
}
旁白:(parent_id) 允许回复评论。
无论如何,为了减少代码重复,我可以创建一个名为 CommentsTrait 的 Trait,它具有上述方法,并由相关模型使用它。十分简单。但问题是,在 Comment class 中,我将不得不硬编码一种方法来定义与博客文章、视频、图像、文档等的关系. 所以基本上,如果我想让另一个模型使用评论,我需要将特征导入该模型,并向 Comment 添加一个方法来设置关系。 不一定 是件坏事,但我想让这个过程更加动态。这样我就可以仅从使用特征的模型(通过包含或不包含它)中转换评论 on/off 就是这样。
那么有没有办法让 Comment 模型可以动态确定(内部或外部,比如使用提供者)哪些模型正在使用特征并设置关系怎么样?
thnx,
克里斯托夫
您只需要 Comment
上的一种关系方法就可以 return 它属于什么。 comments
table 上应该有一个 commentable_id
和一个 commentable_type
字段。 morphTo
关系将从 commentable_type
字段知道它属于哪个模型。您应该只在 Comment
:
上需要此方法
public function commentable()
{
return $this->morphTo();
}
Laravel 8.x Docs - Eloquent - Relationships - Polymorphic Relationships - One to Many morphTo
以这种方式包含动态关系。
Comment::resolveRelationUsing ('video', function ($commentModel) {
return $commentModel->belongsTo(Video::class, 'commentable_id')
->where('commentable_type', Video::class);
//or simple
$commentModel->morphTo()->where(/*... */); // your custom logic
});
您可以根据自己的条件和逻辑将其放在引导特征或服务提供者中。
所以我正在尝试构建功能以允许用户对不同类型的数据发表评论。博客文章、视频、图像、文档、评论(回复)等。因此,每一个都需要定义与 Comments 模型的关系。所以基本上
public function comments()
{
return $this->morphMany(Comment::class, 'commentable')->whereNull('parent_id');
}
旁白:(parent_id) 允许回复评论。
无论如何,为了减少代码重复,我可以创建一个名为 CommentsTrait 的 Trait,它具有上述方法,并由相关模型使用它。十分简单。但问题是,在 Comment class 中,我将不得不硬编码一种方法来定义与博客文章、视频、图像、文档等的关系. 所以基本上,如果我想让另一个模型使用评论,我需要将特征导入该模型,并向 Comment 添加一个方法来设置关系。 不一定 是件坏事,但我想让这个过程更加动态。这样我就可以仅从使用特征的模型(通过包含或不包含它)中转换评论 on/off 就是这样。
那么有没有办法让 Comment 模型可以动态确定(内部或外部,比如使用提供者)哪些模型正在使用特征并设置关系怎么样?
thnx,
克里斯托夫
您只需要 Comment
上的一种关系方法就可以 return 它属于什么。 comments
table 上应该有一个 commentable_id
和一个 commentable_type
字段。 morphTo
关系将从 commentable_type
字段知道它属于哪个模型。您应该只在 Comment
:
public function commentable()
{
return $this->morphTo();
}
Laravel 8.x Docs - Eloquent - Relationships - Polymorphic Relationships - One to Many morphTo
以这种方式包含动态关系。
Comment::resolveRelationUsing ('video', function ($commentModel) {
return $commentModel->belongsTo(Video::class, 'commentable_id')
->where('commentable_type', Video::class);
//or simple
$commentModel->morphTo()->where(/*... */); // your custom logic
});
您可以根据自己的条件和逻辑将其放在引导特征或服务提供者中。