1

I would like to eagerload inverse relation. Business case: I have stories, stories are connected to books over relatedBooks field. Now I would like to query those books only which not have any story.

I do not see any easy way to do it, so I thought that to using eagerload the related stories somehow, and filtering out the nulls What also could help is to just using having count somehow

But I am not able to do it, because I am not able to lead the relatedBooks(inverse) from books perspective, only from stories.

Tried to use the manyToMany plugin, but it is not helping either, just giving a nice interface

Also I know I can query one-by-one but that is silly

(last workaround would be to use hardcoded sql, but I would like to avoid this one:) )

Visky Máté
  • 359
  • 1
  • 11
  • With eagerloading, you're referring to https://docs.craftcms.com/v3/dev/eager-loading-elements.html right? – Urs Sep 12 '18 at 10:01
  • 2
    Is this roughly the same question as https://craftcms.stackexchange.com/q/10456/8325 ? (it has no accepted answer though) – Urs Sep 12 '18 at 10:02
  • Also, you might want to post your current code sample – Urs Sep 12 '18 at 10:02
  • It sounds like you don't need "eager loading." That's a work-around for slow performance issues. You are trying to find entries in a "Books" section that have no relationships to entries in a "Stories" section. Correct? – Alex Roper Sep 14 '18 at 09:38

1 Answers1

1

UPDATE:

in this case you should use :empty:, like this:

{% set orphanBooks = craft.entries.section('books').relatedStories(':empty:') %}

ORIGINAL CONTENT

According to the documentation, you can query the entries using your field handle:

TIP

Most custom fields support element query parameters as well, named after the field handles.

https://docs.craftcms.com/v3/dev/element-queries/#executing-element-queries

You might use :notempty: as a negative selector, just like in this query:

{% set products = craft.entries.section('product').productSale(':notempty:') %}

These SE question and answers might be helpful, too:

Get entries NOT related to categories

Return entries where field is "not empty"

Ottó Radics
  • 421
  • 3
  • 4
  • With your code, you would finde products without a productSale. What the OP wants is productSales that haven't been related to a product (orphans) – Urs Sep 16 '18 at 13:23
  • Yep, you are right: updated my answer. – Ottó Radics Sep 16 '18 at 19:22
  • This will return a list of all books, as no book has a field "relatedStories". The relation is the other way round (inverse). – Urs Sep 17 '18 at 07:41
  • 1
    Well, yeah. In this case Many to Many Field Type might be useful: https://github.com/page-8/craft-manytomany – Ottó Radics Sep 17 '18 at 15:17