Query Builder
메서드 체이닝으로 SQL 쿼리를 안전하게 작성합니다.
조건 조회
where, orderBy, limit
코드
$model = new PostModel();
// 조회수 50 초과, 내림차순 정렬, 최대 3개
$topPosts = $model->where('views >', 50)
->orderBy('views', 'DESC')
->findAll(3);
결과 (조회수 50 초과 게시글)
| 제목 | 작성자 | 조회수 |
|---|---|---|
| 보안 best practice #921 | 홍길동 | 493 |
| PHP 기초 #249 | 이영희 | 365 |
| 캐싱 전략 #720 | 홍길동 | 237 |
집계 함수
selectSum, countAllResults
// 전체 조회수 합산
$totalViews = $model->selectSum('views')->first()->views;
// 전체 게시글 수 (소프트 삭제 제외)
$count = $model->countAllResults();
전체 조회수 합계
1,854
전체 게시글 수
10
GROUP BY
작성자별 통계
$db = \Config\Database::connect();
$result = $db->table('posts')
->select('author, SUM(views) as total_views, COUNT(*) as post_count')
->groupBy('author')
->orderBy('total_views', 'DESC')
->get()->getResultArray();
| 작성자 | 게시글 수 | 총 조회수 |
|---|---|---|
| 홍길동 | 2 | 730 |
| 이영희 | 2 | 463 |
| 박민준 | 1 | 215 |
| 정현우 | 1 | 183 |
| 김철수 | 1 | 142 |
| 최지수 | 1 | 67 |
| 윤서연 | 1 | 54 |
| 아키텍트 | 1 | 0 |