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
$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
Array
(
[0] => 8208
[1] => 8391
[2] => 8394
[3] => 8397
[4] => 8400
[5] => 8403
[6] => 8406
[7] => 8409
[8] => 8412
[9] => 8415
)
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?
Leave a Comment