Giới thiệu vấn đề
Truy vấn Eloquent thường gây overhead khi làm việc với bảng lớn hoặc quan hệ phức tạp. Hiểu cách tối ưu giúp giảm tải DB, cải thiện tốc độ API.
Kỹ thuật giảm số lượng truy vấn
Eager Loading
Sử dụng with() để tải quan hệ cùng lúc, tránh N+1.
$posts = \App\Models\Post::with('comments.author')->get();Select chỉ cần trường
Chỉ lấy các cột cần thiết bằng select(), giảm dữ liệu truyền.
$users = \App\Models\User::select('id','name','email')->where('active',1)->get();Chunk để xử lý dữ liệu lớn
Thay vì all(), dùng chunk() để xử lý từng phần, giảm bộ nhớ.
\App\Models\Order::where('status','pending')->chunk(100, function($orders){
foreach($orders as $order){
// xử lý
}
});Index và tối ưu schema
Thêm index vào cột thường dùng trong where, join, orderBy. Ví dụ:
ALTER TABLE users ADD INDEX idx_email (email);
Sử dụng kiểu dữ liệu phù hợp, tránh VARCHAR(255) cho cột ngắn.
Sử dụng Query Builder cho truy vấn phức tạp
Khi Eloquent không đáp ứng, chuyển sang Query Builder để viết SQL tối ưu.
$result = DB::table('orders')
->join('order_items','orders.id','order_items.order_id')
->where('orders.status','completed')
->groupBy('orders.id')
->select('orders.id', DB::raw('SUM(order_items.price) as total'))
->havingRaw('total > ?', [1000])
->get();Cache kết quả truy vấn
Lưu kết quả thường truy cập vào cache để tránh truy vấn lặp.
$users = Cache::remember('active_users', 600, function(){
return \App\Models\User::where('active',1)->get();
});Kết luận
Áp dụng eager loading, select trường cần, chunk, index, Query Builder và cache sẽ giảm thời gian phản hồi đáng kể. Để nắm vững toàn bộ quy trình và thực hành dự án thực tế, Tham khảo khóa học "Lập trình web PHP & MySQL với Laravel Framework" tại đây.




.png)



