Search code examples
phpsymfonydoctrinerepository

query accessing repository not returning data


Symfony / Doctrine - Repository not returning data.

I have successfully retrieved data from another entity/repository previously, but can't seem to fetch data from this particular repository. I have cleared cache in console and I have registered the repository with the entity class (with annotation).

Testing the DQL as SQL returns results as expected, meaning parameters passed into query will return results I desire through SQL query, just not DQL query.

The one difference between the route that is accessing this repository in comparison to past successful repository queries is the "parameter bag" is being passed through request "attributes" in this repository and in the successful previous repository queries the query parameters were passed through request "query - Parameter Bag" in the request. I am not sure it is even part of the repository query problem however.

The Controller

/**
 * Open the modal dialog for selecting strip width
 * @Route("/select/{materialId}/{gaugeId}/{rangeUpper}/{rangeLower}", defaults={"materialId" = 0, "gaugeId" = 0, "rangeUpper" = 0, "rangeLower" = 0}, name="material-stock_selectWidth")
 * @Method("GET")
 */
public function selectStripWidthAction (Request $request)
{
    $em = $this->getDoctrine()->getManager();

    $materialStocks = $em->getRepository('UniflyteBundle:MaterialStock')->findAllByParams($request);



    return $this->render('materialstock/dialog/select.html.twig', [
        'MaterialStock' => $materialStocks,
    ]);
}

The Repository

public function findAllByParams (Request $request)
{

    $criteria = $request->query->get('uniflytebundle_material-stock_selectWidth');

    $criteria = ($request->get('materialId') == 0 ? [] : ['materialId' => $request->get('materialId')]);
    $criteria = array_merge(($request->get('gaugeId') == 0 ? [] : ['gaugeId' => $request->get('gaugeId')]), $criteria);
    $criteria = array_merge(($request->get('rangeUpper') == 0 ? [] : ['rangeUpper' => $request->get('rangeUpper')]), $criteria);
    $criteria = array_merge(($request->get('rangeLower') == 0 ? [] : ['rangeLower' => $request->get('rangeLower')]), $criteria);
    $criteria = array_filter($criteria);

    $query = $this->createQueryBuilder('ms');

    if (!empty($criteria)) {
        if (!empty($criteria['materialId']) && !empty($criteria['gaugeId']) && !empty($criteria['rangeUpper']) && !empty($criteria['rangeLower'])) {
            $query
              ->where('ms.material = :materialId')
              ->andWhere('ms.gauge = :gaugeId')
              ->andWhere('ms.widthDecimal <= :upperIdentifier')
              ->andWhere('ms.widthDecimal >= :lowerIdentifier')
              ->setParameter('materialId', $criteria['materialId'])
              ->setParameter('gaugeId', $criteria['gaugeId'])
              ->setParameter('upperIdentifier', $criteria['rangeUpper'])
              ->setParameter('lowerIdentifier', $criteria['rangeLower'])
            ;
        }
    }
    return $query->orderBy('ms.widthDecimal', 'DESC');
}

Displaying results

<select>
    {% for MaterialStock in MaterialStock %}
        <option>{{ MaterialStock.widthDecimal }}</option>
    {% endfor %}
</select>

A dump() from the controller showing queryBuilder.

MaterialStockController.php on line 139:
array:1 [▼
"materialStocks" => QueryBuilder {#613 ▼
-_em: EntityManager {#757 …11}
-_dqlParts: array:9 [▼
  "distinct" => false
  "select" => array:1 [▶]
  "from" => array:1 [▶]
  "join" => []
  "set" => []
  "where" => Andx {#642 ▼
    #separator: " AND "
    #allowedClasses: array:4 [▶]
    #preSeparator: "("
    #postSeparator: ")"
    #parts: array:4 [▼
      0 => "ms.material = :materialId"
      1 => "ms.gauge = :gaugeId"
      2 => "ms.widthDecimal <= :upperIdentifier"
      3 => "ms.widthDecimal >= :lowerIdentifier"
    ]
  }
  "groupBy" => []
  "having" => null
  "orderBy" => array:1 [▶]
]
-_type: 0
-_state: 0
-_dql: null
-parameters: ArrayCollection {#646 ▼
  -elements: array:4 [▼
    0 => Parameter {#645 ▼
      -name: "materialId"
      -value: "1"
      -type: 2
    }
    1 => Parameter {#644 ▼
      -name: "gaugeId"
      -value: "7"
      -type: 2
    }
    2 => Parameter {#648 ▼
      -name: "upperIdentifier"
      -value: "3.75"
      -type: 2
    }
    3 => Parameter {#643 ▼
      -name: "lowerIdentifier"
      -value: "3.5"
      -type: 2
    }
  ]
}
-_firstResult: null
-_maxResults: null
-joinRootAliases: []
#cacheable: false
#cacheRegion: null
#cacheMode: null
#lifetime: 0

} ]

Registering Repository in Entity Class

@ORM\Entity(repositoryClass="UniflyteBundle\Repository\MaterialStockRepository")

What am I doing wrong here?

I appreciate any time/energy/thought/suggestions invested on this challenge. Thank you in advance.


Solution

  • You have the query, but you did not get result.

    findAllByParams method should look like that:

    public function findAllByParams ($arguments)
    {
      // query building goes here
      // ...
      $query->orderBy('ms.widthDecimal', 'DESC');
      return $query->getQuery()->getResult()
    }
    

    Don't pass Request to your repository method, get the parameters(and validate them) on the outside, for example, in controller.