3

I'm trying to make a filter inside an overlay_nearest function where I must relate an attribute from the current layer to the overlay layer.

I'm trying to use with_variable to store the outer layer attribute, but for a weird reason it's not working. Can someone shed some light on how to make it work?

This is the expression I'm using (where "ID" is an integer):

with_variable(
    'myId', 
    "ID", 
    overlay_nearest(
         'Lines', 
          $geometry, 
          filter:="ID"=@myId
    )
)

The expression above returns an array with 0 elements, but any of the expressions below work ok:

This shows that with_variable seems to be working correctly as it returns the expected ID -> 80000.

with_variable('myId', "ID", @myId) 

This shows that using the filter with a correct ID also works, as it returns 1 element in the array

with_variable(
    'myId', 
    "ID", 
     overlay_nearest(
         'Lines', 
          $geometry, 
          filter:="ID"=80000
     )
)

So, if @myId has the correct value (80000), and filtering with "ID"=80000 works as expected, why does filtering with "ID"=@myId not work?

2

1 Answer 1

5

See my answer at: https://gis.stackexchange.com/a/477802/129409

Basically, it's a limitation in QGIS. There is a feature request open (https://github.com/qgis/QGIS/issues/43146), so it may become available at some point in the future.

In the meantime, the workaround is to wrap the overlay_nearest function in an eval call.

So rewriting your expression, you get:

with_variable('myId',"ID",
    eval( 'overlay_nearest( \'Lines\', $geometry, filter:="ID"=' || @myId || ' )' )
)
3
  • 2
    Your answer works, but I found out that in this case we can even avoid the usage of with_variable, replacing @myId with the actual "ID" field. The only purpose of the with_Variable was to try to achieve this in the first place. Feb 28 at 23:04
  • 1
    That's interesting @DanielMöller - does raise questions of how with_variable() variables are handled by functions that access other layers. It's the same process, first resolve the value of "ID" then apply it to overlay_nearest(), but it seems like "ID" has to be evaluated as part of a larger expression inside out, rather than stored as a variable.
    – she_weeds
    Feb 29 at 2:08
  • @she_weeds - it doesn't seem to matter whether it's a with_variable(), or just a sub-expression. If it involves other layers, overlay_* doesn't seem to handle it as expected. Pretty sure using a variable (or sub-expression) generally works ok with other semi-complex parent expressions like aggregate. Mar 1 at 3:24

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.