Johnny
Johnny

Reputation: 612

In TYPO3 Extbase Repository use statement and like together

Following function works. But I wanna use "statement" and "like" together. If I comment out the line with constraint1 and try with:

$constraint1 = $query->statement("SELECT * FROM pages WHERE title LIKE '" . $text . "%'");

...the query doesn't work.

I got an error:

1: PHP Catchable Fatal Error: Argument 1 passed to TYPO3\CMS\Extbase\Persistence\Generic\Qom\QueryObjectModelFactory::_or() must implement interface TYPO3\CMS\Extbase\Persistence\Generic\Qom\ConstraintInterface, instance of TYPO3\CMS\Extbase\Persistence\Generic\Query given, called in [...] on line 439 and defined in [...]\typo3\sysext\extbase\Classes\Persistence\Generic\Qom\QueryObjectModelFactory.php line 122

Function:

    /**
    * Test
    *
    * @param string $text
    * @return Objects
    */
    public function findWordsByText($text) {

        $query = $this->createQuery();
        $query->getQuerySettings()->setRespectStoragePage(FALSE);

        $query->getQuerySettings()->setReturnRawQueryResult(TRUE);

        $constraint1 = $query->like('title', $text . '%');
        // $constraint1 = $query->statement("SELECT * FROM pages WHERE title LIKE '" . $text . "%'");

        $constraint2 = $query->like('title', 'new');

        $constraint = array($constraint1, $constraint2);

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

        $records = $query->execute();

        return $records;
    }

If I change follwing lines:

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

To - logicalAnd:

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

...the query is empty.

Upvotes: 0

Views: 6300

Answers (1)

lorenz
lorenz

Reputation: 4558

I don't see your problem. You want to return all records that either contain the term $text in the title field or have 'new' in the title field. So just use a simple logicalOr query:

/**
* Test
*
* @param string $text
* @return Objects
*/
public function findWordsByText($text) {

    $query = $this->createQuery();
    $query->getQuerySettings()->setRespectStoragePage(FALSE);
    $query->getQuerySettings()->setReturnRawQueryResult(TRUE);

    $query->matching(
        $query->logicalOr(
           $query->like('title', '%' . $text . '%'),
           $query->like('title', 'new')
        )
    );

    return $query->execute();
}

$query->statement() is for raw SQL queries and cannot be combined with createQuery.

By the way, if $text comes from a POST or GET input, don't forget to sanitize the input.

Upvotes: 2

Related Questions