1

This seems more like a PHP question than a Craft CMS question, but since it's related to an entry query I'm trying to create I figured someone from the Craft community might know. I'm having trouble creating a query that excludes some IDs that are pulled from another entry field. (It's a blog with a "Featured Entries" field at the top, if there are featured entries, they should be excluded from the feed below.)

My code looks like this:

$excluded = implode(',',$entry->featuredMedia->ids());
$entries = Entry::find()->section('blog');
$entries->id(['not', $excluded);

Which results in an error "Invalid numeric value: 1602,1630" (The IDs of my excluded entries)

Strangely enough, this example works:

$excluded = $entry->featuredMedia->ids();
$entries = Entry::find()->section('blog');
$entries->id(['not', $excluded[0], $excluded[1]]);

I know this has something to do with implode() returning a string instead of numeric values, but I can't figure out how to get the right format.

1 Answer 1

3

The implode function will turn the array of IDs into a comma-separated string. Then you're putting that into an array with 'not' as the first element, so the parameter you're passing to id() looks like this:

['not', '1602,1630']

This isn't one of the supported formats – if you want to exclude a list of IDs, you pass an array of IDs with 'not' as the first element:

['not', 1602, 1630]

Instead of using implode, you can use the array returned by your first query as-is, only adding 'not' at the beginning using array_unshift:

$excluded = $entry->featuredMedia->ids();
array_unshift($excluded, 'not');

$entries = Entry::find()
    ->section('blog')
    ->id($excluded)
    ->all();
1
  • 1
    That worked perfectly and seems obvious in retrospect. Thanks for the help! Jun 23, 2023 at 16:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.