3

I'm trying to exclude a list of ids from a query using an ElementCriteriaModel

This is what I have so far, but it's resulting in nothing coming back when I'm expecting at least 1 result. Is something wrong with my syntax or is my method way off?

$criteria->id = 'and';
for ($i = 0; $i < count($idList); ++$i)
    $criteria->id .= ', not' . $idList[$i];

Also, I've tried removing the $criteria->id = 'and'; to no avail

A nudge in the right direction would be much appreciated

Thanks

6

This should do the trick:

$idList = [1, 2, 3, 4];
$criteria->id = 'and, not ' . implode(', not ', $idList);

In plain text, the id property would then look like this:

'and, not 1, not 2, not 3, not 4'

The syntax may look a little odd, but it essentially makes Craft compile an SQL query with an AND (elements.id!=$elementId) statement for each ID you want to exclude.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy