enzo
enzo

Reputation: 459

Magento 2 - Set collection limit in a Model

I created a model file which I would like a method inside me to return products with a limit.

Below my model:

    <?php

namespace Test\Ice\Model;

class Data extends \Magento\Framework\App\Helper\AbstractHelper {

/**
 * System configuration values
 *
 * @var array
 */
protected $_config;

/**
 * Store manager interface
 *
 */
protected $_storeManager;

/**
 * Product interface
 *
 */
protected $_product;

/**
 * Initialize
 *
 * @param Magento\Framework\App\Helper\Context $context
 * @param Magento\Catalog\Model\ProductFactory $productFactory
 * @param Magento\Store\Model\StoreManagerInterface $storeManager
 * @param Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
 * @param array $data
 */
public function __construct(
    \Magento\Framework\App\Helper\Context $context, 
    \Magento\Catalog\Model\ResourceModel\Product\Collection $collection, 
    \Magento\Store\Model\StoreManagerInterface $storeManager, 
    \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, 
    array $data = []
) {
    $this->_product = $collection;
    $this->_storeManager = $storeManager;
    parent::__construct($context, $data);
}

public function getProducts() {

    $limit = 10;

    return $this->_product->getSelect()->limit($limit);

}

}

The problem is that it does not make the limit, but always returns all products in the collection. Where am I wrong? Thank you

Upvotes: 1

Views: 17415

Answers (1)

Arvind Bhardwaj
Arvind Bhardwaj

Reputation: 5291

Use $this->_product->getCollection()->setPageSize(10)->setCurPag‌​e(1);

Upvotes: 4

Related Questions