Eager load commerce order data in custom ElementExporter for Users I have a custom ElementExporter for users and I'd like to include commerce order data. The below code works, but it's a ton of queries. I don't have a ton of experience with SQL queries, how can this be optimized with eager loading?
public function export(ElementQueryInterface $query): array
{
    $results = [];

    /** @var ElementQuery $query */

    foreach ($query-&gt;each() as $user) {
        /** @var User $user */

        $orderTotal = '';
        $orderDate = '';
        $order = Order::find()
            -&gt;user($user)
            -&gt;hasPurchasables('41599')
            -&gt;orderBy('dateOrdered desc')
            -&gt;dateOrdered('&gt;= 2020-09-01')
            -&gt;isCompleted(true)
            -&gt;one();

        if ($order) {
            $orderTotal = '$' . $order-&gt;totalPrice;
            $orderDate = $order-&gt;dateOrdered-&gt;format('m/d/Y h:iA T');
        }

        $results[] = [
            'Donation Amount' =&gt; $orderTotal ?? '',
            'Donation Date' =&gt; $orderDate ?? '',
        ];
    }

    return $results;
}
Your code looks like it actually has a further problem that you're only fetching the first order for a given user. Rather than eager loading (which is basically creating joins so that the relevant data is fetched in one go), why not use a hash map to look up each customer's set of orders? So, outside your users loop, create a separate query to fetch all orders and use GROUP BY to group them by user id. You can then reference each sub-array by its user id inside the users loop.