Panel: Query structure fields of different pages to find related page

For an archive project, I want to relate a set of paintings to the boxes they’re stored in.

There are two types of pages:

  1. Page per box with a structure field that holds the numbers of paintings physically stored in that box (kiste.yml).

  2. Page per painting. A query should find the box this painting is stored in (werk.yml).

With a custom page model the correct box gets returned in the template:

class WerkPage extends Page
    public function getKiste()
        $kisten = site()->index()->filterBy('intendedTemplate', 'kiste');
        foreach ($kisten as $kiste) 
            $in_kiste = $kiste->archivnummern()->toStructure()->filterBy('archivnummer', $this->uid());
            if ($in_kiste) 
                return $kiste->title();
        return false;

How can this function be called in the blueprint of the painting-page?
This, for example, seems not to work:

        type: select
        options: query
        query: page.getKiste

It returns this:

Invalid query result data

Your function must return a collection or an array, but it either returns false or a single page title.

Also, your if statement will always return true, because even if $in_kiste returns an empty structure collection, it is still a collection.

Can a painting belong to more than one box? If not, then a select field doesn’t make sense.

Thank you, this helps a lot. And sorry about the late answer!

For the if-statement I now use:
if ($in_kiste->count() > 0)

You’re absolutely right that a select field is not the right choice, but it responds to queries. Is there a way to just print the title of the box like an info field or a disabled text field?

Or, using a pages field and returning a pages object:
return new Pages([$kiste->id()]);

Now the related box-page appears as option to be selected in the pages field. Is this possible to make it selected by default? Again, in the painting-page this should only be an information, not something that can (or needs to) be edited.