Magento 2.1 – addAttributeToSelect Not Working with Product Collection

collection;jsonmagento-2.1product-attributeselect

I am applying these fillers:

$collection->addAttributeToSelect('name');
$collection->addAttributeToSelect('sku');

but every time getting full record as comes form:

$collection->addAttributeToSelect('*');

[{"entity_id":"101","attribute_set_id":"9","type_id":"simple","sku":"MH04-XS-White","has_options":"0","required_options":"0","created_at":"2018-10-08 07:35:50","updated_at":"2018-10-08 07:35:50"},{"entity_id":"102","attribute_set_id":"9","type_id":"simple","sku":"MH04-XS-Yellow","has_options":"0","required_options":"0","created_at":"2018-10-08 07:35:50","updated_at":"2018-10-08 07:35:50"},{"entity_id":"103","attribute_set_id":"9","type_id":"simple","sku":"MH04-S-Green","has_options":"0","required_options":"0","created_at":"2018-10-08 07:35:50","updated_at":"2018-10-08 07:35:50"},{"entity_id":"104","attribute_set_id":"9","type_id":"simple","sku":"MH04-S-White","has_options":"0","required_options":"0","created_at":"2018-10-08 07:35:50","updated_at":"2018-10-08 07:35:50"},{"entity_id":"105","attribute_set_id":"9","type_id":"simple","sku":"MH04-S-Yellow","has_options":"0","required_options":"0","created_at":"2018-10-08 07:35:50","updated_at":"2018-10-08 07:35:50"},{"entity_id":"106","attribute_set_id":"9","type_id":"simple","sku":"MH04-M-Green","has_options":"0","required_options":"0","created_at":"2018-10-08 07:35:50","updated_at":"2018-10-08 07:35:50"},{"entity_id":"107","attribute_set_id":"9","type_id":"simple","sku":"MH04-M-White","has_options":"0","required_options":"0","created_at":"2018-10-08 07:35:50","updated_at":"2018-10-08 07:35:50"}]

I am getting collection using class as:

\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory

and

public function getProductCollection()
{
    $collection = $this->_productCollectionFactory->create();
    $collection->addAttributeToSelect('name')->addAttributeToSelect('sku');
    $page = $this->getRequest()->getParam('page');
    $collection->setPageSize(50)->setCurPage($page);
    return json_encode($collection->getData());

}

Best Answer

You should use an array:

$collection->addAttributeToSelect(['name','sku']);

OR

$collection->addAttributeToSelect('name')->addAttributeToSelect('sku');

OR

protected $_productCollection;

public function __construct(
...........
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollection,
...........
) {
    ...........
    $this->_productCollection = $productCollection;
    ...........
}

and

public function getProductCollection()
{
    $collection = $this->_productCollectionFactory->create();
    $collection->getCollection()->addAttributeToSelect(['name','sku']);
    $page = $this->getRequest()->getParam('page');
    $collection->setPageSize(50)->setCurPage($page);
    return json_encode($collection->getData());
}