Developing a "Customers who bought this item also bought" block for 1C-Bitrix

Our company is engaged in the development, support and maintenance of Bitrix and Bitrix24 solutions of any complexity. From simple one-page sites to complex online stores, CRM systems with 1C and telephony integration. The experience of developers is confirmed by certificates from the vendor.
Our competencies:
Development stages
Latest works
  • image_website-b2b-advance_0.png
    B2B ADVANCE company website development
    1177
  • image_bitrix-bitrix-24-1c_fixper_448_0.png
    Website development for FIXPER company
    811
  • image_bitrix-bitrix-24-1c_development_of_an_online_appointment_booking_widget_for_a_medical_center_594_0.webp
    Development based on Bitrix, Bitrix24, 1C for the company Development of an Online Appointment Booking Widget for a Medical Center
    564
  • image_bitrix-bitrix-24-1c_mirsanbel_458_0.webp
    Development based on 1C Enterprise for MIRSANBEL
    747
  • image_crm_dolbimby_434_0.webp
    Website development on CRM Bitrix24 for DOLBIMBY
    655
  • image_crm_technotorgcomplex_453_0.webp
    Development based on Bitrix24 for the company TECHNOTORGKOMPLEKS
    976

"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.