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

Sta*_*lav 6 laravel eloquent

在这个解决方案中,来自 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)

在这种情况下,可注释的方法将返回具体PostVideo模型。

但是如何将所有评论整合为集合,其中每个项目PostVideo模型将在哪里?App\Comment::all()预期从评论表返回记录,这不是我们需要的。

Gay*_*yan 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'); 
    } 
}
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

  • 请不要使用反引号 (\`\`) 来包裹字符串,否则它将不起作用。 (2认同)