14.4. Trabalhando com a tabela de atributos

A tabela de atributos exibe informações sobre as feições de uma camada selecionada. Cada linha da tabela representa uma feição (com ou sem geometria) e cada coluna contém uma informação específica sobre a feição. As feições da tabela podem ser pesquisadas, selecionadas, movidas ou mesmo editadas.

14.4.1. Prefácio: Tabelas espaciais e não espaciais

O QGIS permite carregar camadas espaciais e não espaciais. Atualmente, isso inclui tabelas suportadas pelo OGR e texto delimitado, bem como o provedor PostgreSQL, MSSQL, SpatiaLite, DB2 e Oracle. Todas as camadas carregadas estão listadas no painel: guilabel: Camadas. Se uma camada está espacialmente ativada ou não, determina se você pode interagir com ela no mapa.

As tabelas não espaciais podem ser navegadas e editadas usando a visualização da tabela de atributos. Além disso, eles podem ser usados ​​para pesquisas de campo. Por exemplo, você pode usar colunas de uma tabela não espacial para definir valores de atributos ou um intervalo de valores permitidos para serem adicionados a uma camada vetorial específica durante a digitalização. Dê uma olhada no widget de edição na seção Propriedades do formulário de atributos para descobrir mais.

14.4.2. Apresentando a Interface da Tabela de Atributos

Para abrir a tabela de atributos para uma camada vetorial, ative a camada clicando nela Painel Camadas. Em seguida, no menu principal: seleção de menus: menu Camada, escolha openTable :menuselection: Abrir tabela de atributos. Também é possível clicar com o botão direito do mouse na camada e escolher openTable Abrir Tabela de Atributo no menu suspenso ou clique em openTable :guilabel: botão Abrir tabela de atributos na barra de ferramentas Atributos. Se você preferir atalhos, F6 abrirá a tabela de atributos. Shift+F6 abrirá a tabela de atributos filtrada para os recursos selecionados e: kbd:Ctrl+F6 abrirá a tabela de atributos filtrados para os recursos visíveis.

Isso abrirá uma nova janela que exibe os atributos da feição para a camada (figure_attributes_table). De acordo com a configuração em :menuselection: menu Configurações –> Opções –> Fonte de dados, a tabela de atributos será aberta em uma janela encaixada ou em uma janela regular. O número total de feições na camada e o número de feições atualmente selecionados/filtrados são mostrados no título da tabela de atributos, bem como se a camada é espacialmente limitada.

../../../_images/vectorAttributeTable.png

Fig. 14.68 Tabela de atributos para a camada de regiões

Os botões na parte superior da janela da tabela de atributos fornecem a seguinte funcionalidade:

Tabela 14.1 Ferramentas Disponíveis

Ícone

Etiqueta

Finalidade

Atalho Padrão

toggleEditing

Alternar modo de edição

Habilitar funcionalidades de edição

Ctrl+E

multiEdit

Alternar modo multi edição

Atualize vários campos de várias feições

saveEdits

Salvar Edições

Salvar modificações atuais

refresh

Recarregar a tabela

newTableRow

Adicionar feição

Adicionar nova feição sem geometria

deleteSelectedFeatures

Excluir feições selecionadas

Remover feições selecionadas para a camada

editCut

Cortar feições selecionadas para área de transferência

Ctrl+X

copySelected

Copiar feições selecionadas para a área de transferência

Ctrl+C

editPaste

Colar feições da área de transferência

Inserir novas feições das copiadas

Ctrl+V

expressionSelect

Selecionar feições usando uma expressão

selectAll

Selecionar Todas

Selecionar todas feições em uma camada

Ctrl+A

invertSelection

Seleção invertida

Inverter a seleção atual na camada

Ctrl+R

deselectActiveLayer

Desselecionar todas

Desselecionar todas as feições na camada atual

Ctrl+Shift+A

filterMap

Filtrar/Selecionar feições usando formulário

Ctrl+F

selectedToTop

Mover selecionadas para o topo

Mover linhas selecionadas para o todo da tabela

panToSelected

Mapa panorâmico para selecionar linhas

Ctrl+P

zoomToSelected

Aproximar mapa para selecionar linhas

Ctrl+J

newAttribute

Novo campo

Adicionar um novo campo para uma fonte de dados

Ctrl+W

deleteAttribute

Excluir campo

Remover um campo a partir da fonte de dados

calculateField

Abrir calculadora de campo

Atualização de campo para muitas feições em uma linha

Ctrl+I

conditionalFormatting

Formatação condicional

Ativar formatação de tabela

dock

Tabela de Atributos do Dock

Permite encaixar/desencaixar a tabela de atributos

actionRun

Ações

Listas de ações relatadas para uma camada

Nota

Dependendo do formato dos dados e da biblioteca OGR criada com a sua versão do QGIS, algumas ferramentas podem não estar disponíveis.

Abaixo desses botões está a barra Cálculo de campo rápido (ativada apenas em modo de edição), que permite aplicar rapidamente cálculos a todos ou parte das feições da camada. Esta barra usa o mesmo: ref:expressões<vector_expressions>`como o |calcula campo| :sup:`Calculadora de campo (consulte: ref:` calcule_campos_valores`).

14.4.2.1. Visualização da tabela versus visualização do formulário

O QGIS fornece dois modos de exibição para manipular facilmente os dados na tabela de atributos:

  • O openTable :sup: Visualização da tabela, exibe valores de várias feições em modo tabular, cada linha representando uma feição e cada coluna um campo.

  • The formView Form view shows feature identifiers in a first panel and displays only the attributes of the clicked identifier in the second one. There is a pull-down menu at the top of the first panel where the “identifier” can be specified using an attribute (Column preview) or an Expression. The pull-down also includes the last 10 expressions for re-use. Form view uses the layer fields configuration (see Propriedades do formulário de atributos). You can browse through the feature identifiers with the arrows on the bottom of the first panel. Once you markered the feature in yellow in the list it is selected in yellow on the canvas. Use the zoomToSelected on top of the attribute table to zoom to the feature. Clicking on an entry in the list (without using the rectangles) makes a feature flash in red color once so you can see where it is situated.

Você pode alternar de um modo para outro clicando no ícone correspondente no canto inferior direito da caixa de diálogo.

Você também pode especificar o modo :guilabel: Visualização padrão na abertura da tabela de atributos em :menuselection: menu Configurações -> Opções -> Fonte de Dados. Pode ser ‘Lembrar última visualização’, ‘Tabela’ ou ‘Formulário’.

../../../_images/attribute_table_views.png

Fig. 14.69 Tabela de atributos na exibição de tabela (superior) vs exibição de formulário (inferior)

14.4.2.2. Configurando as colunas

Clique com o botão direito do mouse em um cabeçalho de coluna quando estiver na exibição de tabela para ter acesso a ferramentas que ajudam a configurar o que pode ser exibido na tabela de atributos e como.

Ocultando e organizando colunas e permitindo ações

Ao clicar com o botão direito do mouse em um cabeçalho de coluna, você pode ocultá-lo da tabela de atributos. Para alterar o comportamento de várias colunas ao mesmo tempo, reexibir uma coluna ou alterar a ordem das colunas, escolha Organizar colunas …. Na nova caixa de diálogo, você pode:

  • marque / desmarque as colunas que deseja mostrar ou ocultar

  • arraste e solte itens para reordenar as colunas na tabela de atributos. Observe que essa alteração é para a renderização da tabela e não altera a ordem dos campos na fonte de dados da camada

  • ative uma nova coluna virtual Açõess que exibe em cada linha uma caixa suspensa ou uma lista de ações de cada linha, consulte Propriedades de Ações para obter mais informações sobre ações.

Redimensionando larguras de colunas

A largura das colunas pode ser definida através de um clique com o botão direito do mouse no cabeçalho da coluna e selecione:

  • Defina a largura… para inserir o valor desejado. Por padrão, o valor atual é exibido no widget

  • Autodimensionar para redimensionar da melhor forma possível a coluna.

Também pode ser alterado arrastando o limite à direita do cabeçalho da coluna. O novo tamanho da coluna é mantido para a camada e restaurado na próxima abertura da tabela de atributos.

Classificando colunas

A tabela pode ser classificada por qualquer coluna, clicando no cabeçalho da coluna. Uma seta pequena indica a ordem de classificação (apontar para baixo significa valores decrescentes da linha superior para baixo, apontar para cima significa valores ascendentes da linha superior para baixo). Você também pode optar por classificar as linhas com a opção: guilabel:sort do menu de contexto do cabeçalho da coluna e escrever uma expressão, por exemplo. para classificar a linha usando várias colunas, você pode escrever concat (col0, col1).

Na exibição de formulário, o identificador de feições pode ser classificado usando o sort :guilabel: opção Classificar por expressão de visualização.

Dica

Classificação com base em colunas de diferentes tipos

Tentar classificar uma tabela de atributos com base em colunas de tipos string e numéricos pode levar a resultados inesperados devido à expressão concat(("USE", "ID") retornando valores de string (ou seja,``’Borough105’ < ‘Borough6’). Você pode contornar isso usando, por exemplo, ``concat("USE", lpad("ID", 3, 0)), que retorna 'Borough105' > 'Borough006'.

14.4.2.3. Formatação de células da tabela usando condições

As configurações de formatação condicional podem ser usadas para realçar nas feições da tabela de atributos nos quais você deseja enfatizar, usando condições personalizadas nas feições:

  • geometria (por exemplo, identificando características de várias partes, áreas pequenas ou em uma extensão de mapa definida …);

  • ou valor do campo (por exemplo, comparando valores com um limite, identificando células vazias …).

Você pode ativar o painel de formatação condicional clicando em conditionalFormatting no canto superior direito da janela de atributos na exibição de tabela (não disponível na exibição de formulário).

O novo painel permite que o usuário adicione novas regras para formatar a renderização de radioButtonOnCampo ou radioButtonOffLinha completa. Adicionar nova regra abre um formulário para definir:

  • o nome da regra;

  • uma condição usando qualquer uma das funções construtor de expressões;

  • a formatação: pode ser escolhida de uma lista de formatos predefinidos ou criada com base em propriedades como:

    • cores de fundo e texto;

    • uso de ícone;

    • negrito, itálico, sublinhado ou strikeout;

    • fonte.

../../../_images/attribute_table_conditional_formating.png

Fig. 14.70 Formatação condicional de uma tabela de atributo

14.4.3. Interagindo com feições em uma tabela de atributos

14.4.3.1. Selecionando características

Na exibição de tabela, cada linha da tabela de atributos exibe os atributos de um recurso exclusivo da camada. Selecionar uma linha seleciona o recurso e, da mesma forma, selecionar um recurso na tela do mapa (no caso de camada ativada para geometria) seleciona a linha na tabela de atributos. Se o conjunto de recursos selecionados na tela do mapa (ou tabela de atributos) for alterado, a seleção também será atualizada na tabela de atributos (ou tela do mapa) de acordo.

As linhas podem ser selecionadas clicando no número da linha no lado esquerdo da linha. Múltiplas linhas podem ser marcadas pressionando a tecla: kbd:Ctrl. Uma seleção contínua pode ser feita pressionando a tecla: kbd:Shift e clicando em vários cabeçalhos de linha no lado esquerdo das linhas. Todas as linhas entre a posição atual do cursor e a linha clicada são selecionadas. Mover a posição do cursor na tabela de atributos, clicando em uma célula na tabela, não altera a seleção de linha. Alterar a seleção na tela principal não move a posição do cursor na tabela de atributos.

Na exibição de formulário da tabela de atributos, as feições são identificados por padrão no painel esquerdo pelo valor do campo exibido (consulte: ref: maptips). Esse identificador pode ser substituído usando a lista suspensa na parte superior do painel, selecionando um campo existente ou usando uma expressão personalizada. Você também pode optar por classificar a lista de recursos no menu suspenso.

Clique em um valor no painel esquerdo para exibir os atributos da feição no caminho certo. Para selecionar uma feição, você precisa clicar dentro do símbolo quadrado à esquerda do identificador. Por padrão, o símbolo fica amarelo. Como na exibição de tabela, você pode executar várias seleções de recursos usando as combinações de teclado expostas anteriormente.

Além de selecionar feições com o mouse, você pode executar a seleção automática com base no atributo da feição, usando as ferramentas disponíveis na barra de ferramentas da tabela de atributos, como (consulte a seção: ref:automatic_selection e a seguir para obter mais informações e casos de uso):

  • expressionSelect Selecione por expressão…

  • formSelect Selecionar Feição pelo Valor…

  • deselectActiveLayer Deselect All Features from the Layer

  • selectAll Selecionar Todas as Feições

  • invertSelection Inverter Feições Selecionadas.

Também é possível selecionar recursos usando o :ref: filter_select_form.

14.4.3.2. Filtragem de feições

Depois de selecionar as feições na tabela de atributos, você pode exibir apenas esses registros na tabela. Isso pode ser feito facilmente usando o item Mostrar feições selecionadas na lista suspensa no canto inferior esquerdo da caixa de diálogo da tabela de atributos. Esta lista oferece os seguintes filtros:

  • Mostrar Todas as Feições

  • Mostrar Feições Selecionadas

  • Mostrar Feições visíveis no mapa

  • Mostrar Feições Novas e Editadas

  • Filtro de Campo - permite ao usuário filtrar com base no valor de um campo: escolha uma coluna da lista, digite um valor e pressione :kbd:` Enter` para filtrar. Em seguida, apenas as feições correspondentes são mostrados na tabela de atributos.

  • Filtro avançado (Expressão) - Abre a caixa de diálogo Construtor de expressões. Dentro dele, você pode criar: ref: expressões complexas<vector_expressions> para corresponder às linhas da tabela. Por exemplo, você pode filtrar a tabela usando mais de um campo. Quando aplicada, a expressão do filtro será exibida na parte inferior do formulário.

Também é possível: ref: filtrar recursos usando formulários <filter_select_form>.

Nota

A filtragem de registros da tabela de atributos não filtra feições da camada; eles são simplesmente ocultados momentaneamente da tabela e podem ser acessados ​​na tela do mapa ou removendo o filtro. Para filtros que ocultam recursos da camada, use o Query Builder.

Dica

Atualize a filtragem da fonte de dados com Mostrar feições visíveis no mapa

Quando, por motivos de desempenho, os recursos mostrados na tabela de atributos são espacialmente limitados à extensão da tela em sua abertura (consulte: ref: Opções da fonte de dados<tip_table_filtering> para obter instruções), selecionando: guilabel: Mostrar feições visíveis no mapa em um nova extensão de tela atualiza a restrição espacial.

14.4.3.3. Filtrando e selecionando feições usando formulários

Clicando no filterMap :sup: Filtre/selecione recursos usando o formulário ou pressione :kbd:Ctrl+F` fará com que a caixa de diálogo da tabela de atributos mude para a exibição do formulário e substitua cada widget por sua variante de pesquisa.

A partir deste ponto, a funcionalidade desta ferramenta é semelhante à descrita em: ref: select_by_value, onde é possível encontrar descrições de todos os operadores e selecionar modos.

../../../_images/tableFilteredForm.png

Fig. 14.71 Tabela de atributos filtrada pelo formulário de filtro

Ao selecionar / filtrar feições da tabela de atributos, existe um botão Filtro de feições que permite definir e refinar filtros. Seu uso aciona a opção: guilabel: Filtro avançado (Expressão) e exibe a expressão de filtro correspondente em um widget de texto editável na parte inferior do formulário.

Se já houver feições filtradas, você poderá refinar o filtro usando a lista suspensa ao lado do botão Filtro de feições. As opções são:

  • Filtrar dentro de (“AND”)

  • Estender filtro (“OR”)

Para limpar o filtro, selecione a opção Mostrar todas as feições no menu suspenso inferior esquerdo ou limpe a expressão e clique em Aplicar ou pressione Enter.

14.4.4. Usando ação em feições

Os usuários têm várias possibilidades de manipular feições com o menu contextual, como:

  • Selecionar todas (Ctrl+A) as feições;

  • Copie o conteúdo de uma célula na área de transferência com: guilabel:Copiar conteúdo da célula;

  • Aproximar na feição sem ter que selecioná-lo previamente;

  • Panorâmica da feição sem ter que selecioná-lo previamente;

  • Destacar feição, para destacá-la na tela do mapa;

  • Abrir formulário: alterna a tabela de atributos para a exibição de formulários, com foco na feição clicado.

../../../_images/copyCellContent.png

Fig. 14.72 Copiar botão de conteúdo da célula

Se você deseja usar dados de atributo em programas externos (como Excel, LibreOffice, QGIS ou um aplicativo Web personalizado), selecione uma ou mais linhas e use o copySelected Copie as linhas selecionadas para a área de transferência ou pressione: kbd:Ctrl+C.

Em: menuselection: menu Configurações -> Opções -> Fonte de Dado, você pode definir o formato no qual colar Copiar feições como lista suspensa:

  • Texto simples, sem geometria,

  • Texto simples, geometria WKT,

  • GeoJSON

Você também pode exibir uma lista de ações neste menu contextual. Isso é ativado na guia Propriedades da camada ► Ações. Veja Propriedades de Ações para mais informações sobre ações.

14.4.4.1. Salvando feições selecionadas como nova camada

As feições selecionadas podem ser salvas como qualquer formato vetorial suportado pelo OGR e também transformadas em outro sistema de referência de coordenadas (SRC). No menu contextual da camada, no painel Camadas, clique em Exportar ► Salvar feições selecionadas como… para definir o nome do conjunto de dados de saída, seu formato e SRC (veja a seção Creating new layers from an existing layer). Você notará que checkbox Salvar apenas as feições selecionadas está marcado. Também é possível especificar opções de criação de OGR dentro da caixa de diálogo.

14.4.5. Editando valores de atributo

A edição dos valores dos atributos pode ser feita por:

  • digitando o novo valor diretamente na célula, esteja a tabela de atributos na visualização de tabela ou formulário. As mudanças são feitas célula por célula, feição por feição;

  • using the field calculator: update in a row a field that may already exist or to be created but for multiple features. It can be used to create virtual fields;

  • using the quick field calculation bar: same as above but for only existing field;

  • or using the multi edit mode: update in a row multiple fields for multiple features.

14.4.5.1. Using the Field Calculator

The calculateField Field Calculator button in the attribute table allows you to perform calculations on the basis of existing attribute values or defined functions, for instance, to calculate length or area of geometry features. The results can be used to update an existing field, or written to a new field (that can be a virtual one).

The field calculator is available on any layer that supports edit. When you click on the field calculator icon the dialog opens (see Fig. 14.73). If the layer is not in edit mode, a warning is displayed and using the field calculator will cause the layer to be put in edit mode before the calculation is made.

Based on the Expression Builder dialog, the field calculator dialog offers a complete interface to define an expression and apply it to an existing or a newly created field. To use the field calculator dialog, you must select whether you want to:

  1. apply calculation on the whole layer or on selected features only

  2. create a new field for the calculation or update an existing one.

../../../_images/fieldcalculator.png

Fig. 14.73 Field Calculator

If you choose to add a new field, you need to enter a field name, a field type (integer, real, date or string) and if needed, the total field length and the field precision. For example, if you choose a field length of 10 and a field precision of 3, it means you have 7 digits before the dot, and 3 digits for the decimal part.

A short example illustrates how field calculator works when using the Expression tab. We want to calculate the length in km of the railroads layer from the QGIS sample dataset:

  1. Load the shapefile railroads.shp in QGIS and press openTable Open Attribute Table.

  2. Click on toggleEditing Toggle editing mode and open the calculateField Field Calculator dialog.

  3. Select the checkbox Create a new field checkbox to save the calculations into a new field.

  4. Set Output field name to length_km

  5. Select Decimal number (real) as Output field type

  6. Set the Output field length to 10 and the Precision to 3

  7. Double click on $length in the Geometry group to add the length of the geometry into the Field calculator expression box.

  8. Complete the expression by typing / 1000 in the Field calculator expression box and click OK.

  9. You can now find a new length_km field in the attribute table.

14.4.5.2. Creating a Virtual Field

A virtual field is a field based on an expression calculated on the fly, meaning that its value is automatically updated as soon as an underlying parameter changes. The expression is set once; you no longer need to recalculate the field each time underlying values change. For example, you may want to use a virtual field if you need area to be evaluated as you digitize features or to automatically calculate a duration between dates that may change (e.g., using now() function).

Nota

Use of Virtual Fields

  • Virtual fields are not permanent in the layer attributes, meaning that they’re only saved and available in the project file they’ve been created.

  • A field can be set virtual only at its creation. Virtual fields are marked with a purple background in the fields tab of the layer properties dialog to distinguish them from regular physical or joined fields. Their expression can be edited later by pressing the expression button in the Comment column. An expression editor window will be opened to adjust the expression of the virtual field.

14.4.5.3. Using the Quick Field Calculation Bar

While Field calculator is always available, the quick field calculation bar on top of the attribute table is only visible if the layer is in edit mode. Thanks to the expression engine, it offers a quicker access to edit an already existing field:

  1. Select the field to update in the drop-down list.

  2. Fill the textbox with a value, an expression you directly write or build using the expression expression button.

  3. Click on Update All, Update Selected or Update Filtered button according to your need.

../../../_images/fieldcalculatorbar.png

Fig. 14.74 Quick Field Calculation Bar

14.4.5.4. Editing multiple fields

Unlike the previous tools, multi edit mode allows multiple attributes of different features to be edited simultaneously. When the layer is toggled to edit, multi edit capabilities are accessible:

  • using the multiEdit Toggle multi edit mode button from the toolbar inside the attribute table dialog;

  • or selecting Edit ► multiEdit Modify attributes of selected features menu.

Nota

Unlike the tool from the attribute table, hitting the Edit ► Modify Attributes of Selected Features option provides you with a modal dialog to fill attributes changes. Hence, features selection is required before execution.

In order to edit multiple fields in a row:

  1. Select the features you want to edit.

  2. From the attribute table toolbar, click the multiEdit button. This will toggle the dialog to its form view. Feature selection could also be made at this step.

  3. At the right side of the attribute table, fields (and values) of selected features are shown. New widgets appear next to each field allowing for display of the current multi edit state:

    • multiEditMixedValues The field contains different values for selected features. It’s shown empty and each feature will keep its original value. You can reset the value of the field from the drop-down list of the widget.

    • multiEditSameValues All selected features have the same value for this field and the value displayed in the form will be kept.

    • multiEditChangedValues The field has been edited and the entered value will be applied to all the selected features. A message appears at the top of the dialog, inviting you to either apply or reset your modification.

    Clicking any of these widgets allows you to either set the current value for the field or reset to original value, meaning that you can roll back changes on a field-by-field basis.

    ../../../_images/attribute_multiedit.png

    Fig. 14.75 Editing fields of multiple features

  4. Make the changes to the fields you want.

  5. Click on Apply changes in the upper message text or any other feature in the left panel.

Changes will apply to all selected features. If no feature is selected, the whole table is updated with your changes. Modifications are made as a single edit command. So pressing undo Undo will rollback the attribute changes for all selected features at once.

Nota

Multi edit mode is only available for auto generated and drag and drop forms (see Personalizando um formulário para seus dados); it is not supported by custom ui forms.

14.4.6. Creating one or many to many relations

Relations are a technique often used in databases. The concept is that features (rows) of different layers (tables) can belong to each other.

14.4.6.1. Introducing 1-N relations

As an example you have a layer with all regions of alaska (polygon) which provides some attributes about its name and region type and a unique id (which acts as primary key).

Then you get another point layer or table with information about airports that are located in the regions and you also want to keep track of these. If you want to add them to the regions layer, you need to create a one to many relation using foreign keys, because there are several airports in most regions.

../../../_images/relations1.png

Fig. 14.76 Alaska region with airports

Layers in 1-N relations

QGIS makes no difference between a table and a vector layer. Basically, a vector layer is a table with a geometry. So you can add your table as a vector layer. To demonstrate the 1-n relation, you can load the regions shapefile and the airports shapefile which has a foreign key field (fk_region) to the layer regions. This means, that each airport belongs to exactly one region while each region can have any number of airports (a typical one to many relation).

Foreign keys in 1-N relations

In addition to the already existing attributes in the airports attribute table, you’ll need another field fk_region which acts as a foreign key (if you have a database, you will probably want to define a constraint on it).

This field fk_region will always contain an id of a region. It can be seen like a pointer to the region it belongs to. And you can design a custom edit form for editing and QGIS takes care of the setup. It works with different providers (so you can also use it with shape and csv files) and all you have to do is to tell QGIS the relations between your tables.

Defining 1-N relations

The first thing we are going to do is to let QGIS know about the relations between the layers. This is done in Project ► Properties…. Open the Relations tab and click on signPlus Add Relation.

  • Name is going to be used as a title. It should be a human readable string, describing, what the relation is used for. We will just call say airport_relation in this case.

  • Referenced Layer (Parent) also considered as parent layer, is the one with the primary key, pointed to, so here it is the regions layer. You need to define the primary key of the referenced layer, so it is ID.

  • Referencing Layer (Child) also considered as child layer, is the one with the foreign key field on it. In our case, this is the airports layer. For this layer you need to add a referencing field which points to the other layer, so this is fk_region.

    Nota

    Sometimes, you need more than a single field to uniquely identify features in a layer. Creating a relation with such a layer requires a composite key, ie more than a single pair of matching fields. Use the signPlus Add new field pair as part of a composite foreign key button to add as many pairs as necessary.

  • Id will be used for internal purposes and has to be unique. You may need it to build custom forms. If you leave it empty, one will be generated for you but you can assign one yourself to get one that is easier to handle

  • Relationship strength sets the strength of the relation between the parent and the child layer. The default Association type means that the parent layer is simply linked to the child one while the Composition type allows you to duplicate also the child features when duplicating the parent ones.

../../../_images/relations2.png

Fig. 14.77 Adding a relation between regions and airports layers

From the Relations tab, you can also press the signPlus Discover Relation button to fetch the relations available from the providers of the loaded layers. This is possible for layers stored in data providers like PostgreSQL or SpatiaLite.

Forms for 1-N relations

Now that QGIS knows about the relation, it will be used to improve the forms it generates. As we did not change the default form method (autogenerated) it will just add a new widget in our form. So let’s select the layer region in the legend and use the identify tool. Depending on your settings, the form might open directly or you will have to choose to open it in the identification dialog under actions.

../../../_images/relations3.png

Fig. 14.78 Identification dialog regions with relation to airports

As you can see, the airports assigned to this particular region are all shown in a table. And there are also some buttons available. Let’s review them shortly:

  • The toggleEditing button is for toggling the edit mode. Be aware that it toggles the edit mode of the airport layer, although we are in the feature form of a feature from the region layer. But the table is representing features of the airport layer.

  • The saveEdits button is for saving all the edits.

  • The newTableRow button will add a new record to the airport layer attribute table. And it will assign the new airport to the current region by default.

  • The capturePoint is the same as newTableRow but lets you digitize the airport geometry in the map canvas beforehand. Note that the icon will change according to geometry type.

  • The duplicateFeature button allows you to copy one or more child features.

  • The deleteSelectedFeatures button will delete the selected airport permanently.

  • The link symbol will open a new dialog where you can select any existing airport which will then be assigned to the current region. This may be handy if you created the airport on the wrong region by accident.

  • The unlink symbol will unlink the selected airport from the current region, leaving them unassigned (the foreign key is set to NULL) effectively.

  • With the zoomToSelected button you can zoom the map to the selected child features.

  • The two buttons formView and openTable to the right switch between table view and form view where the later let’s you view all the airports in their respective form.

In the above example the referencing layer has geometries (so it isn’t just an alphanumeric table) so the above steps will create an entry in the layer attribute table that has no corresponding geometric feature. To add the geometry:

  1. Choose openTable Open Attribute Table for the referencing layer.

  2. Select the record that has been added previously within the feature form of the referenced layer.

  3. Use the addPart Add Part digitizing tool to attach a geometry to the selected attributes table record.

If you work on the airport table, the widget Relation Reference is automatically set up for the fk_region field (the one used to create the relation), see Relation Reference widget.

In the airport form you will see the formView button at the right side of the fk_region field: if you click on the button the form of the region layer will be opened. This widget allows you to easily and quickly open the forms of the linked parent features.

../../../_images/relations4.png

Fig. 14.79 Identification dialog airport with relation to regions

The Relation Reference widget has also an option to embed the form of the parent layer within the child one. It is available in the Properties ► Attributes Form menu of the airport layer: select the fk_region field and check the Show embedded form option.

If you look at the feature dialog now, you will see, that the form of the region is embedded inside the airports form and will even have a combobox, which allows you to assign the current airport to another region.

../../../_images/relations5.png

Moreover if you toggle the editing mode of the airport layer, the fk_region field has also an autocompleter function: while typing you will see all the values of the id field of the region layer. Here it is possible to digitize a polygon for the region layer using the signPlus button if you chose the option Allow adding new features in the Properties ► Attributes Form menu of the airport layer.

The child layer can also be used in the Selecionar Feições Por Valor tool in order to select features of the parent layer based on attributes of their children.

In Fig. 14.80, all the regions where the mean altitude of the airports is greater than 500 meters above sea level are selected.

You will find that many different aggregation functions are available in the form.

../../../_images/relation_select_by_value.png

Fig. 14.80 Select parent features with child values

14.4.6.2. Introducing many-to-many (N-M) relations

N-M relations are many-to-many relations between two tables. For instance, the airports and airlines layers: an airport receives several airline companies and an airline company flies to several airports.

This SQL code creates the three tables we need for an N-M relationship in a PostgreSQL/PostGIS schema named locations. You can run the code using the Database ► DB Manager… for PostGIS or external tools such as pgAdmin. The airports table stores the airports layer and the airlines table stores the airlines layer. In both tables few fields are used for clarity. The tricky part is the airports_airlines table. We need it to list all airlines for all airports (or vice versa). This kind of table is known as a pivot table. The constraints in this table force that an airport can be associated with an airline only if both already exist in their layers.

CREATE SCHEMA locations;

CREATE TABLE locations.airports
(
   id serial NOT NULL,
   geom geometry(Point, 4326) NOT NULL,
   airport_name text NOT NULL,
   CONSTRAINT airports_pkey PRIMARY KEY (id)
);

CREATE INDEX airports_geom_idx ON locations.airports USING gist (geom);

CREATE TABLE locations.airlines
(
   id serial NOT NULL,
   geom geometry(Point, 4326) NOT NULL,
   airline_name text NOT NULL,
   CONSTRAINT airlines_pkey PRIMARY KEY (id)
);

CREATE INDEX airlines_geom_idx ON locations.airlines USING gist (geom);

CREATE TABLE locations.airports_airlines
(
   id serial NOT NULL,
   airport_fk integer NOT NULL,
   airline_fk integer NOT NULL,
   CONSTRAINT airports_airlines_pkey PRIMARY KEY (id),
   CONSTRAINT airports_airlines_airport_fk_fkey FOREIGN KEY (airport_fk)
      REFERENCES locations.airports (id)
      ON DELETE CASCADE
      ON UPDATE CASCADE
      DEFERRABLE INITIALLY DEFERRED,
   CONSTRAINT airports_airlines_airline_fk_fkey FOREIGN KEY (airline_fk)
      REFERENCES locations.airlines (id)
      ON DELETE CASCADE
      ON UPDATE CASCADE
      DEFERRABLE INITIALLY DEFERRED
 );

Instead of PostgreSQL you can also use GeoPackage. In this case, the three tables can be created manually using the Database ► DB Manager…. In GeoPackage there are no schemas so the locations prefix is not needed.

Foreign key constraints in airports_airlines table can´t be created using Table ► Create Table… or Table ► Edit Table… so they should be created using Database ► SQL Window…. GeoPackage doesn’t support ADD CONSTRAINT statements so the airports_airlines table should be created in two steps:

  1. Set up the table only with the id field using Table ► Create Table…

  2. Using Database ► SQL Window…, type and execute this SQL code:

    ALTER TABLE airports_airlines
       ADD COLUMN airport_fk INTEGER
       REFERENCES airports (id)
       ON DELETE CASCADE
       ON UPDATE CASCADE
       DEFERRABLE INITIALLY DEFERRED;
    
    ALTER TABLE airports_airlines
       ADD COLUMN airline_fk INTEGER
       REFERENCES airlines (id)
       ON DELETE CASCADE
       ON UPDATE CASCADE
       DEFERRABLE INITIALLY DEFERRED;
    

Then in QGIS, you should set up two one-to-many relations as explained above:

  • a relation between airlines table and the pivot table;

  • and a second one between airports table and the pivot table.

An easier way to do it (only for PostgreSQL) is using the Discover Relations in Project ► Properties ► Relations. QGIS will automatically read all relations in your database and you only have to select the two you need. Remember to load the three tables in the QGIS project first.

../../../_images/relations6.png

Fig. 14.81 Relations and autodiscover

In case you want to remove an airport or an airline, QGIS won’t remove the associated record(s) in airports_airlines table. This task will be made by the database if we specify the right constraints in the pivot table creation as in the current example.

Nota

Combining N-M relation with automatic transaction group

You should enable the transaction mode in Project Properties ► Data Sources ► when working on such context. QGIS should be able to add or update row(s) in all tables (airlines, airports and the pivot tables).

Finally we have to select the right cardinalilty in the Layer Properties ► Attributes Form for the airports and airlines layers. For the first one we should choose the airlines (id) option and for the second one the airports (id) option.

../../../_images/relations7.png

Fig. 14.82 Set relationship cardinality

Now you can associate an airport with an airline (or an airline with an airport) using Add child feature or Link existing child feature in the subforms. A record will automatically be inserted in the airports_airlines table.

../../../_images/relations8.png

Fig. 14.83 N-M relationship between airports and airlines

Nota

Using Many to one relation cardinality

Sometimes hiding the pivot table in an N-M relationship is not desirable. Mainly because there are attributes in the relationship that can only have values when a relationship is established. If your tables are layers (have a geometry field) it could be interesting to activate the On map identification option (Layer Properties ► Attributes Form ► Available widgets ► Fields) for the foreign key fields in the pivot table.

Nota

Pivot table primary key

Avoid using multiple fields in the primary key in a pivot table. QGIS assumes a single primary key so a constraint like constraint airports_airlines_pkey primary key (airport_fk, airline_fk) will not work.