文章转发自专业的Laravel开发者社区,原始连接: https://learnku.com/laravel/t...
Eloquent 有一个不为人知的函数叫 withCount():它能够帮助获取包括远程一对多关系在内的对象关联的记录条数。接下来看示例。php
在咱们的示例小项目中,咱们有三个模型:User,Post 以及 Comment。全部的关联关系均可以用这三个模型来举例描述,先看 app/User.php 模型:laravel
public function posts() { return $this->hasMany(Post::class); } public function comments() { return $this->hasManyThrough(Comment::class, Post::class); }
如今,咱们来尝试在页面上显示以下的表格 - 用户及他们的文章和评论的统计列表:app
实现很简单,下面是控制器 UserController 的代码:函数
public function index() { $users = User::withCount(['posts', 'comments'])->get(); return view('users', compact('users')); }
传递到 withCount() 方法的每个参数,最终都会在模型实例中建立一个参数名添加了 _count 后缀的属性。所以,在上面的例子中,能够经过访问 $user->posts_count** 和 **$user->comments_count 属性来获取统计数值。post
而后,在咱们的视图文件中,咱们有:this
<table class="table"> <thead> <tr> <th>User</th> <th class="text-center">Posts</th> <th class="text-center">Comments</th> </tr> </thead> <tbody> @foreach ($users as $user) <tr> <td>{{ $user->name }}</td> <td class="text-center">{{ $user->posts_count }}</td> <td class="text-center">{{ $user->comments_count }}</td> </tr> @endforeach </tbody> </table>
注意, withCount() 既能够处理 hasMany() 关系,也能够处理hasManyThrough().的第二级深度。spa
不只如此,咱们甚至能够在使用 withCount() 时指定关联模型的过滤条件。假设,咱们有一个评论表(comments),包含一个审核状态(approved)的字段。下面的示例展现了如何对该字段进行过滤,甚至能够指定一个别名:3d
$users = User::withCount([ 'posts', 'comments', 'comments as approved_comments_count' => function ($query) { $query->where('approved', 1); }]) ->get();
如此,即可在试图中使用 $user->approved_comments_count 来展现统计数据。code
若想了解更多关于 withCount() 方法的信息 – 可查看 Laravel 官方文档。对象