文章轉發自專業的Laravel開發者社區,原始連接:learnku.com/laravel/t/2…php
Eloquent 有一個不爲人知的函數叫 withCount():它能夠幫助獲取包括遠程一對多關係在內的對象關聯的記錄條數。接下來看示例。laravel
在咱們的示例小項目中,咱們有三個模型:User,Post 以及 Comment。全部的關聯關係均可以用這三個模型來舉例描述,先看 app/User.php 模型:bash
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->comments_count 屬性來獲取統計數值。post
而後,在咱們的視圖文件中,咱們有:ui
<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().的第二級深度。this
不只如此,咱們甚至能夠在使用 withCount() 時指定關聯模型的過濾條件。假設,咱們有一個評論表(comments),包含一個審覈狀態(approved)的字段。下面的示例展現瞭如何對該字段進行過濾,甚至能夠指定一個別名:spa
$users = User::withCount([
'posts',
'comments',
'comments as approved_comments_count' => function ($query) {
$query->where('approved', 1);
}])
->get();
複製代碼
如此,即可在試圖中使用 $user->approved_comments_count 來展現統計數據。code
若想了解更多關於 withCount() 方法的信息 – 可查看 Laravel 官方文檔。