QGIS – Getting Attribute Value from Parent Layer to Child Layer Using Shared UniqueID

qfieldqgisrelationship-class

CONTEXT

My data consists of a Point-shp (parent layer), a table (child layer), and a 1-N relation between these layers. The point layer represents trees. In this point-layer there is an attribute called Plot_ID, indicating where the tree is located.

After creating a tree, several characteristics of the tree can be inserted (CREATING FEATURES IN CHILD LAYER), each characteristic created would be a feature in the table layer.

QUESTION

In the child layer there is also a specific column for indicating the Plot_ID. Now, I'd like to copy the attribute value of the specific feature of the parent layer to the feature that is being created from the child layer. This is, if parent is called e.g. 'A', the features from the child from this parent 'A', will copy this Plot_ID.

For aclaration, the process would consist as follows:

1) Create point

1.1) Fill atributes:

fid = 1

uniqueID = 2abc-3cde-4fgh

Plot_ID = P1

2) Create feature in child layer

2.1) Fill attributes:

fid = 1

fk_field = 2abc-3cde-4fgh

Plot_ID = P1 –> through an automatic expression

What I'm looking for is to automatically set an expression that gets the attribute value of the parent layer (Plot_ID), when creating a feature in the child layer. Then, everytime I create a point, and then a child feature, it will automatically get the attribute value Plot_ID from its parent feature.

What I've tried

I've already tried approaches like 1., relation_aggregate, and expressions like attribute(@parent, 'Plot_ID'), but none of them gave me the result I was looking for. In the case of relation_aggregate, the relation between my two layers was somehow not recognized and gave me no value as an output (found no solution about this in internet either).

  1. Aggregating child features with parent attribute values in QGIS

Best Answer

You shouldn't aggregate values, because you said the relationship is one-to-many. So there will only be one tree with the same uniqueID as the current characteristic fk_field, and from that tree you want to extract the Plot_ID attribute:

attribute( get_feature( 'trees', 'uniqueID', current_value( 'fk_field')), 'Plot_ID')

Both relation_aggregate function and @parent variable will not work here because they are intended to be used in parent table, where you can aggregate child features.

The expression was tested in memory layers and it work. Might be problems in not-database providers when trying to create a new child feature from the parent form, when the parent feature is not already saved.

Related Question