Eloquent:如何获得所有多态模型?

问题描述 投票:0回答:1

在 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()
预期会从评论表中返回记录,这不是我们需要的。

laravel eloquent
1个回答
2
投票

官方文档还提到了我们应该如何构建我们的类

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

© www.soinside.com 2019 - 2024. All rights reserved.