TYPO3 v12 Repository, query with constraints
Asked Answered
P

2

5

Since TYPO3 v12 the use of constraints in the repository query is not working like before.

public function findByDate(
   $dateFrom = null, 
   $dateTill = null, 
   $isAdmin = false, 
   $tags = [], 
   $keyword = ''
): QueryResultInterface
{
   $query = $this->createQuery();
   $query->getQuerySettings()->setIgnoreEnableFields(TRUE);
   $query->getQuerySettings()->setEnableFieldsToBeIgnored(['starttime','endtime']);

   $constraints = [];
   if ($keyword != '') {
      $constraints[] = $query->like('titel', '%'.$keyword.'%' );
   }else{
      if (isset($dateFrom) && isset($dateTill)) {
         $constraints[] = $query->logicalAnd(
            $query->lessThan('startdate', $dateTill->getTimestamp()),
            $query->greaterThan('startdate', $dateFrom->getTimestamp()),
         );
      }
   }

   if (count($tags) > 0) {
      $constraints[] = $query->logicalOr(
         $query->in('tags.uid', $tags)
      );
   }

   if ($isAdmin == false) {
      $constraints[] = $query->equals('share', true);
   }

   $query->matching($query->logicalAnd($constraints));
   return $query->execute();
}

Error

TYPO3\CMS\Extbase\Persistence\Generic\Query::logicalAnd(): Argument #1 must be of type TYPO3\CMS\Extbase\Persistence\Generic\Qom\ConstraintInterface, array given

output of the constraints:

Is there still a way to use constraints?

  • Query with one condition is working
  • LogicalAnd with 2 constraints directly also works
Pachisi answered 15/9, 2023 at 18:46 Comment(0)
Y
14

The signature has changed. Instead of putting the array of constraints to logicalAnd() use the spread operator ....

Replace

$query->matching($query->logicalAnd($constraints));

with

$query->matching($query->logicalAnd(...array_values($constraints)));

EDIT 1

Added array_values() guard to avoid associative key unpacking with newer PHP versions.

Yggdrasil answered 15/9, 2023 at 19:0 Comment(0)
P
-2

Found the error - leaving the Brackets the datatype will be Array.

$constraints[] = $query->like('titel', '%'.$keyword.'%' );

instead:

$constraints = $query->like('titel', '%'.$keyword.'%' );

Datatype has to be

\TYPO3\CMS\Extbase\Persistence\Generic\Qom\LogicalAnd
Pachisi answered 15/9, 2023 at 19:14 Comment(1)
The code from the question has multople checks and may collect up multiple constraints. Therefore, it's an array. If you simply change the like constraint collection to set $constraints to a object class, throwing away collected constraints .. and living with the danger, that collecting code afterwards would override that again you will have broken code. Therefore, this is not a "correct" answer for the given code example. In my answer I mentioned the core signature change and the spread operator needs to be used instead of passing an array. That do not destroy findByDate.Bengaline

© 2022 - 2024 — McMap. All rights reserved.