1

My scenario is I have entries in sectionA these are related to entries in sectionB. I want to be able to show all entries from sectionA which are not related to any entry in sectionB.

SectionB has an Entries field which only relates entries from SectionA. I need to query sectionA which are not related from sectionB.

Is there a nice way to get these entries without having to compare IDs arrays or loop through to check each entry?

1 Answer 1

1

If the relation is (a) confined to a single field in sectionA and (b) that field can only relate to sectionB entries, you can just query for entries without a relation in that field using the :empty: parameter:

{% set sectionAEntriesWithoutRelation = craft.entries()
    .section('sectionA')
    .related_section_b(':empty:')
    .all()
%}

Replace related_section_b with the name of the Entries field.


If you're looking for a solution that works for relations across multiple fields or for fields that may also relate to other sections, it's complicated. You can either use a patchy solution involving multiple queries – for example, get ALL sectionB entry IDs, get all sectionA entry IDs related to those and then exclude those from the final query. Or you can use a custom .where() condition – but that get's complicated fast, especially since element queries use a subquery to filter eligible entries and additional conditions are added to either the main query and/or the subquery in unintuitive ways. Look at the relations table to get started.

3
  • Thanks @MoritzLost I updated the question to give context about the setup. I need to query sectionA where a field in sectionB does not have any relation to sectionA. I am guessing it maybe a where clause which may need to be done. I didn't want to grab ID and compare then as there are 1000's of them, it feels it would be more performant to be able to query sectionA where no entry is related to a specific field in sectionB
    – zizther
    Commented Nov 6, 2021 at 0:19
  • @zizther Ok I see, the :empty: selector won't help if the relationship field is not set on the entries you're querying for. Looks like natively there's no way around a custom query then. Or maybe you could check out the Reverse Relations plugin – I haven't tried it, but it's supposed to save relations in both directions, that could make querying much easier.
    – MoritzLost
    Commented Nov 8, 2021 at 10:11
  • Thanks I will take a look. Would be nice to find a way where it wouldn't have to do additional lookups and comparisons.
    – zizther
    Commented Nov 9, 2021 at 13:19

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.