İçeriğe geç

Döngü İçinde Sorgu (ARCH3064)

Anahtar typescript.orm.query-inside-loop · Önem warning · Kategori orm

Döngü gövdesinde herhangi bir DB okuma sorgusu (ad-hoc find, aggregate, repository çağrısı) çalıştırmak öğe başına round-trip üretir. Sorguyu döngü dışına alın veya toplu çekin.

for (const id of productIds) {
const stock = await stockRepo.findOneBy({ productId: id }); // tur başına sorgu
totals.push(stock?.quantity ?? 0);
}
const stocks = await stockRepo.find({ where: { productId: In(productIds) } });
const byId = new Map(stocks.map(s => [s.productId, s.quantity]));
const totals = productIds.map(id => byId.get(id) ?? 0);

Döngüdeki sorguları tek bir toplu sorguya (In/whereIn) çevirip sonuçları bellekte eşleyin.