Magento – Why Magento addAttributeToSelect Never Works

magento-2.1modelproduct-collection

Ok I have faced this issue in magento 1 too and I am not able to understand why addAttributeToSelect(*) never works.

When I call my product collection I want the collection will all the possible attributes.

Here is the product code

    protected $productCollection;

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

    public function execute() {

        //this does not works
        $this->productCollection->addAttributeToSelect(['*']);

        $this->productCollection->addAttributeToSelect('*');

        $this->productCollection->addAttributeToSelect(['*'], 'inner');


        // If I call each attribute individually it will work
        $this->productCollection->addAttributeToSelect(['name', 'image'], 'inner');
    }

If I see the magento Magento\Catalog\Model\ResourceModel\Product\Collection class it has the code but still it does not work

public function addAttributeToSelect($attribute, $joinType = false)
    {
        if ($this->isEnabledFlat()) {
            if (!is_array($attribute)) {
                $attribute = [$attribute];
            }
            foreach ($attribute as $attributeCode) {
                if ($attributeCode == '*') {
                    foreach ($this->getEntity()->getAllTableColumns() as $column) {
                        $this->getSelect()->columns('e.' . $column);
                        $this->_selectAttributes[$column] = $column;
                        $this->_staticFields[$column] = $column;
                    }
                } else {
                    $columns = $this->getEntity()->getAttributeForSelect($attributeCode);
                    if ($columns) {
                        foreach ($columns as $alias => $column) {
                            $this->getSelect()->columns([$alias => 'e.' . $column]);
                            $this->_selectAttributes[$column] = $column;
                            $this->_staticFields[$column] = $column;
                        }
                    }
                }
            }
            return $this;
        }
        return parent::addAttributeToSelect($attribute, $joinType);
    }

why It does not works and what can be the way around that I need not load each and every item of collection again to get all data.

Best Answer

That worked for me all the time.

$this->productCollection->addAttributeToSelect(array('*'))->load();

also look at this addAttributeToSelect in magento2