1

I'm trying to get all the entries which have tags associated with them.

At the moment I'm doing:

$entries = Entry::find()->with('tags')->all();

and then filtering the results in PHP as follows:

$filteredEntries = array_filter($entries, function($entry) {
    return count($entry['tags']) > 0;
});

This works fine, but I am still fetching all the entries, even without tags from the DB - I think this can be more efficient if I can specify in my query that I only want the entries with tags associated to them. How can I do this?

1 Answer 1

1

What you are looking for is the relatedTo parameter (docs) and this post will also help.

If you wanted to return any entries which has (any) tags attached, you could do:

$entries = Entry::find()->tags(':notempty:')->all();

Where tags is the handle of your tags field.

2
  • I've used the relatedTo parameter when trying to find a post with a specific tag - for example Entry::find()->relatedTo($tag)->all(); where $tag is a particular tag - how would I abstract this to find a post with any tag though?
    – Alk
    Commented Nov 12, 2019 at 11:42
  • Just edited my answer above.
    – Oli
    Commented Nov 12, 2019 at 14:45

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.