0

getFirstItem is not working on a collection while getData returns a row.

$product_obj       = $objectManager->create('Magento\Catalog\Model\Product');
$productCollection = $product_obj->getCollection()->addAttributeToFilter('erp_vc_item_code',$value->getVcItemCode());

print_r($productCollection->getSize()); // Prints 1
print_r($productCollection->getData()); // Prints an array
print_r($productCollection->getFirstItem()->getData()); // Does not prints anything
print_r($productCollection->getFirstItem()->getSku()); // Does not prints anything

Output

1

Array
(
  [0] => Array
    (
        [entity_id] => 2087
        [attribute_set_id] => 4
        [type_id] => simple
        [sku] => Mouthwash---Fresh-To-Go-500ml
        [has_options] => 0
        [required_options] => 0
        [created_at] => 2022-03-27 16:31:08
        [updated_at] => 2022-03-27 16:31:09
        [erp_vc_item_code] => PCMO0000258
    )

)

Array
(
)

Sometimes the function works at other places but don't know why it does't work every time as expected.

5
  • I suggest to use \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory for create product collection instead of call getCollection method from product. Jun 8, 2022 at 2:41
  • When it doesn't work then check with flush the cache. If it works after flush the cache, you need to use \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory because it creates object every time and updated the data.
    – Mital Shah
    Jun 8, 2022 at 9:05
  • how about if I have to filter the result by an attribute value? Jun 8, 2022 at 22:28
  • In my case, the getFirstItem() returning 2 items, which must not happen. Is there any alternate for getFirstItem?
    – MSQ
    Aug 15, 2022 at 8:03
  • Did you tried addAttributeToSelect('*') on getCollection method? Aug 15, 2022 at 8:18

2 Answers 2

0

Methods getSize, getData and getFirstItem use different logic

getSize

Calculates totals based on COUNT query

    /**
     * Get collection size
     *
     * @return int
     */
    public function getSize()
    {
        if ($this->_totalRecords === null) {
            $sql = $this->getSelectCountSql();
            $this->_totalRecords = $this->_totalRecords ?? $this->getConnection()->fetchOne($sql, $this->_bindParams);
        }
        return (int)$this->_totalRecords;
    }

getData

Loads items data without convert them into objects

    /**
     * Get all data array for collection
     *
     * @return array
     */
    public function getData()
    {
        if ($this->_data === null) {
            $this->_renderFilters()->_renderOrders()->_renderLimit();
            $select = $this->getSelect();
            $this->_data = $this->_fetchAll($select);
            $this->_afterLoadData();
        }
        return $this->_data;
    }

getFirstItem

Try to load collection and returns first element. Returns empty entity if items is empty

    /**
     * Retrieve collection first item
     *
     * @return DataObject
     */
    public function getFirstItem()
    {
        $this->load();

        if (count($this->_items)) {
            reset($this->_items);
            return current($this->_items);
        }

        return $this->_entityFactory->create($this->_itemObjectClass);
    }

For debug your case I suggest to do:

  1. Run $productCollection->load(true); and check query

  2. Print count($productCollection->getItems()); - maybe you have empty items

2
  • Function getSize returns 1 and getData returns the array. So what is the solution to get the collection object. I know I can use loop to traverse the array but I wanted an uniformity. Based on your debug logic it prints me the SQL query, and on PhpMyAdmin it does not returns any row. Jun 8, 2022 at 22:25
  • You need to understand, why your query returns empty result. You can add to question as well. If you want some universal solution i suggest to create new Product instance and use loadByAttribute method to load entity. Using collection for your logic is overhead and looks like you have some extra logic behind scene. I tried to clarify how each used method works and why it doesn't work in some case. Jun 8, 2022 at 23:14
0

Try this:

<?php
     $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
     $productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection');
     $collection = $productCollection->addAttributeToSelect('*')->setPageSize(10);
     print_r($collection->getFirstItem()->getData();
?>
1

Your Answer

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

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