Skip to content

Commit

Permalink
refactoring withOrder
Browse files Browse the repository at this point in the history
  • Loading branch information
summerblue committed Oct 23, 2019
1 parent 6df9e09 commit ea3e4a3
Show file tree
Hide file tree
Showing 3 changed files with 5 additions and 3 deletions.
1 change: 1 addition & 0 deletions app/Http/Controllers/CategoriesController.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ public function show(Category $category, Request $request, Topic $topic, User $u
// 读取分类 ID 关联的话题,并按每 20 条分页
$topics = $topic->withOrder($request->order)
->where('category_id', $category->id)
->with('user', 'category') // 预加载防止 N+1 问题
->paginate(20);
// 活跃用户列表
$active_users = $user->getActiveUsers();
Expand Down
5 changes: 4 additions & 1 deletion app/Http/Controllers/TopicsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@ public function __construct()

public function index(Request $request, Topic $topic, User $user, Link $link)
{
$topics = $topic->withOrder($request->order)->paginate(20);
$topics = $topic->withOrder($request->order)
->with('user', 'category') // 预加载防止 N+1 问题
->paginate(20);

$active_users = $user->getActiveUsers();
$links = $link->getAllCached();

Expand Down
2 changes: 0 additions & 2 deletions app/Models/Topic.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,6 @@ public function scopeWithOrder($query, $order)
$query->recentReplied();
break;
}
// 预加载防止 N+1 问题
return $query->with('user', 'category');
}

public function scopeRecentReplied($query)
Expand Down

0 comments on commit ea3e4a3

Please sign in to comment.