I've added custom fields to sales_order
Now I want to return them in customerOrders
GraphQL query as a value from database.
How can I do it without fetching the order from database again in Resolver
class?
It's pretty simple - just add your field to the graphql in custom module and add a resolver which could use already loaded order model to get desired data.
etc/schema.graphqls
type CustomerOrder {
my_custom_field: String
@resolver(class: "MageWorx\\ExtendedCartGraphQl\\Model\\Resolver\\OrderCustomField")
}
Model/Resolver/OrderCustomField.php
<?php
/**
* Copyright © MageWorx. All rights reserved.
* See LICENSE.txt for license details.
*/
declare(strict_types=1);
namespace MageWorx\ExtendedCartGraphQl\Model\Resolver;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
class OrderCustomField implements \Magento\Framework\GraphQl\Query\ResolverInterface
{
/**
* @inheritDoc
*/
public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null)
{
if (!isset($value['model'])) {
throw new LocalizedException(__('"model" value should be specified'));
}
/** @var \Magento\Sales\Api\Data\OrderInterface $order */
$order = $value['model'];
return (string)$order->getData('your_custom_field');
}
}
Here is my example module on GitHub. I used the customer
query with orders
because the customerOrders
query is deprecated. Here is example of request:
{
customer {
orders {
total_count
items
{
id
order_date
my_custom_field
}
}
}
}
and response:
{
"data": {
"customer": {
"orders": {
"total_count": 7,
"items": [
{
"id": "MTc=",
"order_date": "2022-05-01 18:11:38",
"my_custom_field": ""
},
{
"id": "MTk=",
"order_date": "2022-05-02 09:35:00",
"my_custom_field": ""
},
{
"id": "MjA=",
"order_date": "2022-05-02 19:29:30",
"my_custom_field": ""
},
{
"id": "MjE=",
"order_date": "2022-05-02 19:34:42",
"my_custom_field": ""
},
{
"id": "MjI=",
"order_date": "2022-05-03 08:32:20",
"my_custom_field": ""
},
{
"id": "MjU=",
"order_date": "2022-05-05 17:13:03",
"my_custom_field": ""
},
{
"id": "MzA=",
"order_date": "2022-05-28 12:41:00",
"my_custom_field": ""
}
]
}
}
}
}
vendor/magento/module-sales-graph-ql/Model/Resolver/CustomerOrders.php
Magento formatting all orders using this line of code: $ordersArray[] = $this->orderFormatter->format($orderModel);
and Inside it adds an Order model to each entity.
Commented
May 31, 2022 at 11:50
customerOrders
query is required I'll recommend you to create an around plugin for Magento\SalesGraphQl\Model\Resolver\Orders::resolve
and fully rewrite this method, but it is strongly not recommended.
Commented
May 31, 2022 at 11:57