Search code examples
phpshopware6

getProduct()->getTag() return null, when it should return tags associated to the Product


In my project, we have products that has tag called serviceItem. Those item with that tag when ordered should be separated by the quantity into individuals order.

It issue is that getTags() returns null, and getTagIds gets "Call to a member function getTagIds() on null" when it gets to the next loop.

Is there a reason for why getTags() returns null?

private function transformOrderLines(OrderEntity $order): array
    {
        /**
         * TODO: If we need to send advanced prices,
         * the price value of the the lines array should be changed to caldulate the advanced price,
         * with the built in quantity calculator
         */
        $lines = [];
        foreach ($order->getLineItems() as $orderLine) {
            $hasDsmServiceItemTag    = $orderLine->getProduct()->getTags();

      
        $lines[] = [
            'name'     => $orderLine->getLabel(),
            'sku'      => substr($orderLine->getProduct()->getProductNumber(), 0, 19),
            'price'    => (string) ($orderLine->getProduct()->getPrice()->first()->getNet()
                * $order->getCurrencyFactor()), //gets original price, calculates factor
            'quantity' => (string) $orderLine->getQuantity()
        ];
      
    }
    $shipping = $this->transformShipping($order);
    if ($shipping) {
        $lines = array_merge($lines, $shipping);
    }

    return $lines;
}`

I also tried $orderLine->getProduct()->getTags()->getName() it also return "Call to a member function getTags() on null"


Solution

  • The problem is wherever the $order is fetched from the DB the orderLineItem.product.tag association is not included in the criteria.

    For performance reasons shopware does not lazily load all association when you access them on entities, but you have to exactly define which associations should be included when you fetch the entities from the database.

    For the full explanation take a look at the docs.