Overriding related-product collection. My aim is to set limit for related product display. Related-products are not displayed if there are less than 10 products, the maximum number of products that can be displayed - 20, more than 20 related-products should not be displayed. But if there are less than 10 products, do not need to display related-products at all.

I need support, please explain or show details, how can I do this using sql queries in a collection ? (not a template) Here is my class in which I am trying to do this:

class Related extends \Magento\Catalog\Block\Product\ProductList\Related

     * I set limit here 
    const RELATED_LIMIT = 20;

    public function __construct(
        \Magento\Catalog\Block\Product\Context $context,
        \Magento\Checkout\Model\ResourceModel\Cart $checkoutCart,
        \Magento\Catalog\Model\Product\Visibility $catalogProductVisibility,
        \Magento\Checkout\Model\Session $checkoutSession,
        \Magento\Framework\Module\Manager $moduleManager,
        array $data = []
    ) {
        $this->_checkoutCart = $checkoutCart;
        $this->_catalogProductVisibility = $catalogProductVisibility;
        $this->_checkoutSession = $checkoutSession;
        $this->moduleManager = $moduleManager;

     * Prepare data
     * added limit for collection
     * @return $this
    protected function _prepareData()
        $product = $this->getProduct();
        /* @var $product \Magento\Catalog\Model\Product */

        $this->_itemCollection = $product->getRelatedProductCollection()->addAttributeToSelect(

        //limit number of products

        if ($this->moduleManager->isEnabled('Magento_Checkout')) {


        foreach ($this->_itemCollection as $product) {

        return $this;

1 Answer 1


In order to not display related product if count is less than 10, override getItems() function in your preference file as below

 * Get collection items
 * @return Collection
public function getItems()
    if ($this->_itemCollection === null) {
    // code to check collection size
    if($this->_itemCollection->getSize() < 10){
        $this->_itemCollection = null;
    return $this->_itemCollection;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.