2017-10-15 14 views
0

我无法找到问题出在哪里。我有postscomments表。在comments表中我加了foreign keypost_id。现在,当我收到所有帖子时,我想要同时收到评论。调用未定义的方法App Post :: withCount()

这里是我的PostController

public function show_api() 
{ 
    return $this->withCount('comments')->get(); 
} 

public function comments() 
{ 
    return $this->hasManyThrough(Comment::class); 
} 

CommentController

public function post() 
{ 
    return $this->belongsTo(Post::class); 
} 

哪里是我的错?

+1

你有没有在控制器中定义这些关系?而不是在模型中? –

+0

是的只是在控制器 – MRustamzade

+1

@MRustamzade你也使用'hasManyThrough'这不会在这里工作。 –

回答

4

我想你已经定义的控制,而不是模型,这些关系。 你应该在各自的模型中定义这些关系,然后它应该工作。

+0

是的,你是对的:)哦,男人。谢谢 – MRustamzade

+1

很高兴我可以帮助:) –

1

在这种情况下,你应该使用hasMany关系:

class Post extends Model 
{ 
    public function comments() 
    { 
     return $this->hasMany(Comment::class); 
    } 
} 

那么这将工作:

Post::withCount('comments')->get(); 
相关问题