In this tutorial, I’ll demonstrate how to fetch specific column values from a collection, using a practical example with Magento 2’s Vendor module.
Working with collections is a common task in Magento 2 development. Collections allow developers to retrieve data from the database in a structured way.
Practical Use Cases
The ability to fetch specific column values is useful in many scenarios:
- Retrieving product SKUs from a product collection.
- Extracting customer emails for targeted marketing.
- Generating reports by pulling specific attributes from orders or invoices
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 |
$collection = $om->create( "Jigar\CustomCollectionDemo\Model\ResourceModel\Vendor\Collection" ); $collection->addAttributeToFilter("group_id", [ "eq" => 33 ]); //feteching column values by specifying key $customerIds = $collection->getColumnValues("user_customer_id"); //print the output array print_r($customerIds); |
Above code demonstrates how to fetch the user_customer_id
column values from a custom vendor collection, filtered by a specific group_id
.
Running this code will display the desired customer IDs in array format.
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
Array ( [0] => 8208 [1] => 8391 [2] => 8394 [3] => 8397 [4] => 8400 [5] => 8403 [6] => 8406 [7] => 8409 [8] => 8412 [9] => 8415 [10] => 8421 [11] => 8424 [12] => 8427 [13] => 8430 [14] => 8466 [15] => 8472 [16] => 8475 [17] => 8919 [18] => 8958 [19] => 8961 [20] => 9024 [21] => 9081 [22] => 9135 ) |
Fetching specific column values from a collection in Magento 2 is a straightforward yet powerful capability. Whether you’re working on product data, customer records, or custom entities, this approach simplifies the process and keeps your code clean.
That’s it for this tutorial, see you soon in the next blog,
Subscribe to my newsletter to get instant updates and weekly newsletter filled with amazing magento 2 tips, tricks & tutorials, direct to your inbox.
You may also like,
How to Install the Hyvä Theme in Magento 2
How to Call a Static Block in XML in Magento 2
How to Create Draggable Dynamic Rows in Magento 2 System Configuration
How to Remove a Link from the Customer Account Menu in Magento 2?