I am trying to exclude terms in my search when using the element api. I have successfully managed to include terms and search them by fields in my entries. I would now like to be able to exclude different terms in those fields.
In this case 'recipeIngredients' is a matrix field.
Here is my criteria search so far :
//Get search query text
$searchQuery = Craft::$app->request->getQueryParam('searchQuery');
//Search in either title or ingredients
if ($searchQuery) $criteria['search'] = "title:'".$searchQuery."' OR recipeIngredients:'".$searchQuery."'";
//Get excluded ingredients query
$excludedQuery = Craft::$app->request->getQueryParam('xq');
if ($excludedQuery) {
if (!isset($criteria['search'])) {
$criteria['search'] = '';
} else {
$criteria['search'] = $criteria['search'].' AND ';
}
$criteria['search'] = $criteria['search']."recipeIngredients: not '".$excludedQuery."'";
}
//Get result count
$count = Craft::$app->request->getQueryParam( 'count' );
$count = $count ? $count : 10;//Default to ten if no parameter
return [
'elementType' => Entry::class,
'criteria' => $criteria,
'elementsPerPage' => $count,
'transformer' => function ( Entry $entry ) {
return [
'name' => $entry->title,
'url' => $entry->url,
//'json_url' => UrlHelper::url( "recipe/{$entry->id}.json" ),
'picture_url' => $entry->recipeImage->one()->getUrl(),
'portions' => (float)$entry->recipePortions,
'time' => [
'total' => (float)$entry->recipeTotalTime
]
];
},
];
I can't figure out if I should be trying to append the excluded terms to the search query, and my syntax is wrong, or if there is another criteria property available to exclude results.
Also, the ElementQuery page mentionned in the docs no longer exists. I assume, it's this page, but I'm not certain.
- recipeIngredients:
parseParam
function and custom fields to the documentation. Now I can link to this page in about every third answer :-P