How To

Magento 2: How to Get Custom Column Value of Order using GraphQL

Hello Magento Friends,

In today’s blog, I will explain How to Get Custom Column Value of Order using GraphQL in Magento 2.

By adding custom columns to orders, merchants can capture and store extra data, facilitating better order management and analysis. With GraphQL, you can craft tailored queries to fetch precisely the data you need, minimizing overhead and optimizing performance. Leverage GraphQL to fetch custom column values of orders in Magento 2, thereby enhancing your store’s capabilities.

Now, let’s dive into the practical aspect of retrieving custom column values of orders using GraphQL in Magento 2.

Steps to Get Custom Column Value of Order using GraphQL in Magento 2:

Step 1: First, we need to create a “schema.graphqls” file inside the etc folder

app\code\Vendor\Extension\etc\

Now, add the code as below

type Query {
    customerOrders: CustomerOrders @resolver(class: "Vendor\\Extension\\Model\\Resolver\\Orders") @deprecated(reason: "Use the `customer` query instead.") @cache(cacheable: false)
}
type CustomerOrders @doc(description: "The collection of orders that match the conditions defined in the filter.") {
    items: [CustomerOrder]! @doc(description: "An array of customer orders.")
    page_info: SearchResultPageInfo @doc(description: "Contains pagination metadata.")
    total_count: Int @doc(description: "The total count of customer orders.")
}
type CustomerOrder  { 
    custom_fee: Float  @deprecated(reason: "Use the `custom_fee` field instead.")
}

Step 2: After that, create the “Orders.php” file inside the Resolver folder.

app\code\Vendor\Extension\Model\Resolver\

Now, include the code as mentioned below

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */declare(strict_types=1);

namespace Vendor\Extension\Model\Resolver;

use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Exception\GraphQlAuthorizationException;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Magento\GraphQl\Model\Query\ContextInterface;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\ResourceModel\Order\CollectionFactoryInterface;

/**
 * Orders data reslover
 */class Orders implements ResolverInterface
{
    /**
     * @var CollectionFactoryInterface
     */    private $collectionFactory;

    /**
     * @param CollectionFactoryInterface $collectionFactory
     */    public function __construct(
        CollectionFactoryInterface $collectionFactory
    ) {
        $this->collectionFactory = $collectionFactory;
    }

    /**
     * @inheritDoc
     */    public function resolve(
        Field $field,
        $context,
        ResolveInfo $info,
        array $value = null,
        array $args = null
    ) {
        /** @var ContextInterface $context */        if (false === $context->getExtensionAttributes()->getIsCustomer()) {
            throw new GraphQlAuthorizationException(__('The current customer isn\'t authorized.'));
        }

        $items = [];
        $orders = $this->collectionFactory->create($context->getUserId());

        /** @var Order $order */        foreach ($orders as $order) {
            $items[] = [
                'id' => $order->getId(),
                'increment_id' => $order->getIncrementId(),
                'order_number' => $order->getIncrementId(),
                'created_at' => $order->getCreatedAt(),
                'grand_total' => $order->getGrandTotal(),
                'status' => $order->getStatus(),
                'custom_fee' => $order->getCustomFee(),
                'model' => $order
            ];
        }
        return ['items' => $items];
    }
}

Step 3: Now run the upgrade command and compile command, then pass the query like below in the server.

{
  customerOrders {
    items {
      order_number
      id
      created_at
      grand_total
      status
      custom_fee
    }
  }
}

Output:

Conclusion:

By harnessing the power of GraphQL in Magento 2, merchants can seamlessly retrieve custom column values of orders, empowering them with deeper insights and streamlined workflows.

Related tutorial – 

How to Get System Configuration Value using GraphQL API in Magento 2

If you have any doubt, share it with me through the comment box and I will be quick to provide you with the solution. Stay in touch with us for more such Magento 2 tutorials.

Happy Coding!

Click to rate this post!
[Total: 1 Average: 5]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

Recent Posts

How to Get Database Value in Shopify Theme App Extension using App Proxy?

In this article, we will learn about how to get database value in the Shopify…

2 days ago

Mastering Tailwind CSS in Laravel: A Comprehensive Guide

Tailwind CSS has emerged as a powerful utility-first CSS framework, offering developers a unique approach…

4 days ago

React Native or Flutter in 2024

The mobile app development field has witnessed a rapid revolution over the past few years.…

6 days ago

Magento 2: How To Call JS on the Checkout Page?

Hello Magento mates, Today we will learn to add a call JS on the checkout…

1 week ago

Boost Your SEM Game: Unveiling the Top 10 Tools for Marketers in 2024

Business survival in today’s digital world has become extremely difficult. Using traditional marketing techniques is…

1 week ago

Five Essential Payroll Compliance Tips for eCommerce Startups

Are you setting up a payroll system for your eCommerce startup? Ensuring compliance with myriad…

2 weeks ago