3

I want to get only one field data in my custom module collection. For ex:

getting following data in collection:

Array
   (
[0] => Array
    (
        [banner_id] => 1
        [banner_title] => Banner 1
        [banner_image] => banner_banner/4/_/4.jpg
        [banner_status] => 0
        [banner_link] => http://google.com
        [banner_sortorder] => 1
    )

)

getting this array in collection response. I need only one value in collection response banner_image. I don't want all the data in collection response. How can i do that?

Is there any method that allows me to fetch only that specific field data instead of loading entire collection?

I want following result only:

   Array
   (
   [0] => Array
    (

        [banner_image] => banner_banner/4/_/4.jpg

    ),
   [2] => Array
    (

        [banner_image] => banner_banner/2/_/892.jpg

    )

)

3 Answers 3

7

Can you just try this?

$collection = $customObject->getCollection()->addFieldToSelect('banner_image');

addFieldToSelect('column_name') will work here I think.

2
  • Will it take low time to generate the response? or it will take same time to load?
    – jack
    Commented Jul 13, 2018 at 8:54
  • This is the ideal way to select any column from the collection. It will take the same time to load. The only way I guess better than this is to use SQL query, which is not a proper way out. Commented Jul 13, 2018 at 9:06
11

Magento has an inbuilt function on Magento\Framework\Data\Collection which provide a specific field value from the collection.

You have to use getColumnValues($colName) for getting the specific field value

$collectionObject->addFieldToSelect('banner_image')->getColumnValues('banner_image')

2
  • Will it take low time to generate the response? or it will take same time to load?
    – jack
    Commented Jul 13, 2018 at 8:54
  • And if I want to get multiple columns? Commented Mar 5, 2020 at 15:21
-1

Here is your solution :-

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $categoryCollection = $objectManager->create('\Magento\Catalog\Model\Category');
    $collection = $categoryCollection->getCollection()->addFieldToFilter('name','MyCards');
    if($collection->count()) {
        return $collection->getFirstItem();
    }else{
      return false;
    }
1
  • Using above code you are filtering the collection which is not going to work. It will show only one value i want entire collection of banner image not only one value.filter will not work. Just check my question again. I have updated what output i am expecting in collection result.
    – jack
    Commented Jul 13, 2018 at 7:02

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.