在这个解决方案中,来自 Laralvel/Eloquent 的官方文档(多态关系)
posts
id - integer
title - string
body - text
videos
id - integer
title - string
url - string
comments
id - integer
body - text
commentable_id - integer
commentable_type - string
Run Code Online (Sandbox Code Playgroud)
我们可以检索帖子或视频:
$post = App\Post::find(1)或者 $post = App\Post::all()
我们可以得到具体的评论
$comment = App\Comment::find(1);
$commentable = $comment->commentable;
Run Code Online (Sandbox Code Playgroud)
在这种情况下,可注释的方法将返回具体Post或Video模型。
但是如何将所有评论整合为集合,其中每个项目Post或Video模型将在哪里?App\Comment::all()预期从评论表返回记录,这不是我们需要的。
官方文档还提到了我们应该如何构建我们的类
class Comment extends Model
{
/** * Get all of the owning commentable models. */
public function commentable()
{
return $this->morphTo();
}
}
class Post extends Model
{
/** * Get all of post's comments. */
public function comments()
{
return $this->morphMany('App\Comment', 'commentable');
}
}
class Video extends Model
{
/** * Get all of the video's comments. */
public function comments()
{
return $this->morphMany('App\Comment', 'commentable');
}
}
Run Code Online (Sandbox Code Playgroud)
这样做之后,我们可以得到帖子的评论,例如
$posts = Post::with('comments')->get();
$videos = Video::with('comments')->get();
Run Code Online (Sandbox Code Playgroud)
$all = $videos->merge($posts)->unique('id');
Run Code Online (Sandbox Code Playgroud)
$allposts包含和的所有评论videos。
| 归档时间: |
|
| 查看次数: |
3179 次 |
| 最近记录: |