"Frequently Bought Together" Block Development for 1C-Bitrix
"Frequently bought together" is a block that shows products actually purchased alongside the current product within the same order. It's not "similar products" and not "recently viewed" — it's co-purchase statistics. A properly implemented block increases the average order value because it suggests what the buyer genuinely needs in the context of the selected product.
Data Source: Bitrix Order Tables
Data comes from real orders. Key tables:
-
b_sale_order— orders (status, date, user). -
b_sale_basket— order line items (product, quantity, price).
Logic: find all orders containing product A, then look at which other products appeared in those same orders. The more frequent — the higher in recommendations.
SELECT
b2.product_id AS recommended_id,
COUNT(DISTINCT b2.order_id) AS co_purchase_count
FROM b_sale_basket b1
JOIN b_sale_order o ON b1.order_id = o.id
AND o.canceled = 'N'
AND o.status_id NOT IN ('F') -- exclude cancelled statuses
JOIN b_sale_basket b2 ON b1.order_id = b2.order_id
AND b2.product_id != b1.product_id
AND b2.product_id IS NOT NULL
WHERE
b1.product_id = :productId
AND o.date_insert >= DATE_SUB(NOW(), INTERVAL 90 DAY)
GROUP BY b2.product_id
HAVING co_purchase_count >= 3 -- minimum threshold for reliability
ORDER BY co_purchase_count DESC
LIMIT 20;
The 90-day selection window ensures that assortment changes are reflected in recommendations more quickly.
Pre-Calculation and Cache
Running this SQL on every product page load is not feasible — too heavy for an active catalog. Pre-calculate for the top-N products and save the result.
CREATE TABLE custom_co_purchases (
product_id INT NOT NULL,
recommended_id INT NOT NULL,
score INT NOT NULL,
calculated_at DATETIME DEFAULT NOW(),
PRIMARY KEY (product_id, recommended_id),
INDEX idx_product (product_id)
);
A Bitrix agent runs once per day during nighttime, recalculating the table for products sold in the last 90 days.
// Agent in local/php_interface/init.php
function RecalcCoPurchasesAgent(): string {
$topProducts = getTopSellingProducts(500); // top 500 products
foreach ($topProducts as $productId) {
$recs = calcCoPurchases($productId);
saveToCoPurchases($productId, $recs);
}
return 'RecalcCoPurchasesAgent();'; // agent continues
}
Display Component
Create component company:catalog.co_purchases in local/components/:
// component.php
if (!\Bitrix\Main\Loader::includeModule('iblock') || !\Bitrix\Main\Loader::includeModule('catalog')) {
return;
}
$productId = (int)$arParams['PRODUCT_ID'];
$limit = (int)($arParams['LIMIT'] ?? 8);
// Read from cache
$cache = \Bitrix\Main\Data\Cache::createInstance();
if ($cache->initCache(3600, "co_purchases_{$productId}_{$limit}", '/co_purchases')) {
$arResult = $cache->getVars();
} elseif ($cache->startDataCache()) {
$recommendedIds = getFromCoPurchasesTable($productId, $limit);
$arResult = getProductsByIds($recommendedIds);
$cache->endDataCache($arResult);
}
$this->IncludeComponentTemplate();
Filtering and Recommendation Validity
Before display, filter recommended products:
function filterValidRecommendations(array $productIds): array {
if (empty($productIds)) return [];
// Only active products with non-zero stock
$filter = [
'ID' => $productIds,
'ACTIVE' => 'Y',
'>CATALOG_QUANTITY' => 0,
];
$result = [];
$res = \CIBlockElement::GetList([], $filter, false, false, ['ID']);
while ($row = $res->Fetch()) {
$result[] = $row['ID'];
}
return $result;
}
If a product doesn't have enough co-purchases (e.g. a new product) — show products from the same category as a fallback.
Cold Start
For new products or stores with limited order history — use content-based fallback:
function getRecommendations(int $productId, int $limit): array {
$coPurchases = getFromCoPurchasesTable($productId, $limit);
if (count($coPurchases) >= $limit) {
return $coPurchases;
}
// Fill in with products from the same category
$needed = $limit - count($coPurchases);
$exclude = array_merge([$productId], $coPurchases);
$categoryFill = getSameCategoryProducts($productId, $needed, $exclude);
return array_merge($coPurchases, $categoryFill);
}
Cart Display
The block also works in the cart — "frequently bought with items in your cart". Logic: take all cart products, merge their recommendations, rank by total score, exclude items already in the cart.
$basketItems = \Bitrix\Sale\Basket::loadItemsForFUser(\Bitrix\Sale\Fuser::getId());
$basketIds = [];
foreach ($basketItems as $item) {
$basketIds[] = $item->getProductId();
}
$allRecs = [];
foreach ($basketIds as $id) {
$recs = getFromCoPurchasesTable($id, 20);
foreach ($recs as $rec) {
$allRecs[$rec['recommended_id']] = ($allRecs[$rec['recommended_id']] ?? 0) + $rec['score'];
}
}
// Exclude items already in the cart
foreach ($basketIds as $id) unset($allRecs[$id]);
arsort($allRecs);
$topRecs = array_slice(array_keys($allRecs), 0, 8);
Timeline
| Stage | Timeline |
|---|---|
| Co-purchase SQL calculation + table | 1–2 days |
| Pre-calculation agent | 1–2 days |
| Component with caching and fallback | 2–3 days |
| Cart block | 1–2 days |
| Testing and threshold tuning | 1–2 days |
Total: 1–1.5 weeks.







