在laravel5.3之后可以使用withCount()这个方法。

注意:一定要是5.3版本之后,5.2和5.1都会报方法未定义

举个栗子:

App\Post::withCount('comments')->get();

使用该方法后,会在模型中添加一个comments_count属性,所以你就可以直接访问该属性就可以了得到统计数了。

foreach ($posts as $post) {
    echo $post->comments_count;
}
你可以像添加约束条件到查询一样来添加多个关联关系的“计数”:
$posts = Post::withCount(['votes', 'comments' => function ($query) {
    $query->where('content', 'like', 'foo%');
}])->get();

相关文章:

  • 2022-12-23
  • 2021-08-27
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-27
  • 2021-08-09
  • 2021-08-15
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-12
  • 2022-02-10
  • 2022-12-23
  • 2022-02-09
相关资源
相似解决方案