Querying using the relationship field

I’m using Kirby to display products that come in different sizes. The sizes are defined as a structure field on another page called ‘Sizes’ with an Engineer field. Not all sizes (S, M, L) are available for each product so I was hoping to use the Relationship field to query only the sizes available for that product. Currently, I’m looping over all the sizes, how can I query this loop based on the selection in the Relationship field? I’m struggling to piece my two bit of logic together, any guidance would be really appreciated.

sizes.yml

  sizes:
    type: engineer
    fields:
      size:
        label: Size
        type: text
        required: true
      amount:
        label: Amount
        type:  text
        icon: gbp
        required: true

A var_dump($sizes)produces:

object(Field)#163 (3) {
  ["page"]=>
  string(5) "sizes"
  ["key"]=>
  string(5) "sizes"
  ["value"]=>
  string(381) "-
  size: "Small"
  amount: "150"
-
  size: "Medium"
  amount: "600"
-
  size: "Large"
  amount: "1200"
}

product.yml

  sizeselector:
    label: Sizes
    type: relationship
    options:
      small: Small
      medium: Medium
      large: Large

product.php (controller)

return function($site, $pages, $page) {
    $sizes = page('sizes')->sizes();
    $size_selector = $page->sizeselector()->split();

    return compact('sizes', 'sizeselector');
};

An example selection, var_dump($size_selector) outputs:

array(2) {
  [0]=>
  string(6) "medium"
  [1]=>
  string(5) "large"
}

product.php (template)

Here I would only want to output the medium and larges sizes based on the previous selection.

<select>
    <?php foreach($sizes->yaml() as $size):?>
        <option data-size="<?php echo $size['size'] ?>" value="<?php echo $size['amount'] ?>"><?php echo $size['size'] ?> — <?= $symbol ?><?php echo $size['amount'] ?> </span></option> 
    <?php endforeach ?>
</select>

If you use toStructure()instead of yaml() you can filter your $sizes collection like this:

$sizes = $page->parent()->sizes()->toStructure();

$size_selector = $page->sizeselector()->split(',');
$realSizes = $sizes->filter(function($item) use($size_selector){
  return in_array(str::lower($item->size()), $size_selector);
});
dump($realSizes);

Ok, I think managed a solution.

<select>
    <?php foreach($sizes->yaml() as $size): ?>
        <?php if(in_array(str::slug($size['size']), $size_selector)):?>
            <option data-size="<?php echo $size['size'] ?>" value="<?php echo $size['amount'] ?>"><?php echo $size['size'] ?> — <?= $symbol ?><?php echo $size['amount'] ?> </span></option> 
        <?php endif; ?>
     <?php endforeach ?>
</select>