Question

I have a product-repository and wish to integrate a searchfield to compare product names and partnumber against.

Comparing against the name only is working fine but I struggle with adding the second field to compare against.

I have certain criteria that must be fulfilled so until now I use the logicalAnd(), which would result in the searchterm to match against both, the name and partnumber.

/**
 * action findBySearchterm
 *
 * @param \string $term
 * @param \boolean $isFrontend
 * @return object
 */
public function findBySearchterm($term, $isFrontend) {
    $userView = $isFrontend ? 'visibleFrontend' : 'visibleBackend';

    $query = $this->createQuery();

    $matching = array(
        $query->like('name', "%$term%"),
        $query->equals($userView, 1),
        $query->equals('deleted', 0),
        $query->equals('hidden', 0),
    );

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

    $query->setOrderings(array('partno' => \TYPO3\CMS\Extbase\Persistence\Generic\Query::ORDER_ASCENDING));
    return $query->execute();
}

I tried to first match an array with searchterms only first (via logicalOr) and then the other criteria afterwards to no avail.

Like this:

public function findBySearchterm($term, $isFrontend) {
    $userView = $isFrontend ? 'visibleFrontend' : 'visibleBackend';

    $query = $this->createQuery();

    $searchterms = array(
        $query->like('name', "%$term%"),
        $query->like('partno', "%$term%"),
    );

    $query->matching($query->logicalOr($searchterms));

    $criteria = array(
        $query->equals($userView, 1),
        $query->equals('deleted', 0),
        $query->equals('hidden', 0),
    );

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

    $query->setOrderings(array('partno' => \TYPO3\CMS\Extbase\Persistence\Generic\Query::ORDER_ASCENDING));
    return $query->execute();
}

But this returns ALL products with no filter at all.

Any help is very much appreciated!

// EDIT Following lorenz suggestion this is the code that works now:

$query->matching( $query->logicalAnd( array(
    $query->logicalOr( array(
        $query->like('name', "%$term%"),
        $query->like('partno', "%$term%"),
    ) ),
    $query->logicalAnd( array(
        $query->equals($userView, 1),
        $query->equals('deleted', 0),
        $query->equals('hidden', 0),
    ) ),
) ) );
Was it helpful?

Solution

You need to have one additional layer to compare for the "enable fields" and the query:

$query->matching->logicalAnd(
  $query->logicalOr(
    $query->like('name', "%$term%"),
    $query->like('partno', "%$term%")
  ),
  $query->logicalAnd(
    $query->equals($userView, 1),
    $query->equals('deleted', 0),
    $query->equals('hidden', 0)
  )
);

So both the search part (name, partno) and the "enable fields" part (deleted, hidden) need to match for a record to be in the result.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top