Filter collection by structure field (and sort)

I’m sure this has come up already but still I’m struggeling.
Trying to filter a collection of pages by a set of uids that are stored in a structure field:

$gesamtbestand = collection('gesamtbestand_aktiv');
$eintraege = $page->eintraege()->toStructure();

The structure field contains two fields:

  type: structure
      type: text
      type: number

…where stueck contains uid-values. Now I’d like to something like this:

$gelistete = $gesamtbestand->filterBy($eintraege->stueck());

And additionally:

$gelistete = $gelistete->sortBy($eintraege->position());

Thanks – and sorry if this question is redundant.

Why do you need the complete collection if you only want the eintraege?

It’s a tool where the user can build custom lists of items.

To begin with, all available items are displayed. The collection holds these available items. The user can choose from here and add items to his list.

The user-list and the available items are displayed side by side.

Now if the user adds an item to his list, it becomes an entry in the structure field (eintraege->stueck). Also, this item disappears from the list of available items. This is why I’d like to filter out the eintraege from the collection.

  1. to reduce the list of available items (what’s selected isn’t available anymore)
  2. to get the page objects of the selected items from the collection

But maybe I’m overcomplicating things?

So stueck is actually a pages field, not a text field, right?

Ah, interesting. No, it was a text field that stored only a string. But as you very rightly suggested, a pages field makes more sense here – instead of the structure field that is, because in fact the eintraege are related pages.

I modified the logic and ended up with a simple solution using a pages field. The selected items can now be retrieved by the toPages() method:

$gelistete = $page->eintraege()->toPages();

With that, filtering the master collection is easy:

$verfuegbare = $gesamtbestand->filterBy('id', 'not in', $gelistete->pluck('id'));

Thank you for pointing me in the right direction! :grinning:
Now I’ll look into programmatically adding and removing entries to the pages field.