在 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
我们可以检索帖子或视频:
$post = App\Post::find(1)
或 $post = App\Post::all()
我们可以得到具体的评论
$comment = App\Comment::find(1);
$commentable = $comment->commentable;
在这种情况下,可注释方法将返回具体的
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');
}
}
这样做后,我们可以获得帖子的评论,例如
$comments = Comments::with('commentable')->get();
$comments
包含所有评论,在每个评论中您可以检索$comment->commentable
,其中包含Post
或Video
。