3

I have two layers:

  1. nomen : point layer
  2. nomenclature : polygon layer

In PostGIS, when adding a point, you must take the nomenclature value by intersection with the polygons layer and insert it in the nomen field.

In QGIS, in the attributes form of the point layer, I use the default expression for the nomen field:

array_to_string(overlay_intersects('polygons', "nomenclature"))

It works as expected, but I need it to be a function of the PostGIS database.

1
  • Hello and welcome to GIS SE. Can you clarify your question ? Layer names are 'point' & 'polygon', attributes are "nomen" and "attribute". I understand the QGIS experssion does what you want it to do (set "nomen" of the points to "nomenclature"). In PostGIS, you want to run a query which does the same ?
    – Kasper
    Commented Feb 3, 2023 at 13:31

1 Answer 1

6

You have to create a trigger.

Test and trigger creation below :

-- DROP TABLE IF EXISTS public.nomen;
-- DROP TABLE IF EXISTS public.nomenclature;
CREATE TABLE public.nomen (nomen SMALLINT, geom GEOMETRY(POINT, 2154));
CREATE TABLE public.nomenclature (nomenclature SMALLINT, geom GEOMETRY(POLYGON, 2154));

-- Trigger part
CREATE OR REPLACE FUNCTION func_trigger_nomen()
  RETURNS trigger AS
$$
BEGIN
     NEW.nomen = (SELECT poly.nomenclature
     FROM nomenclature poly
     WHERE ST_CONTAINS(poly.geom, NEW.geom)
     LIMIT 1);
     RETURN NEW;
END;
$$
LANGUAGE 'plpgsql';

CREATE TRIGGER trigger_nomen
  BEFORE INSERT OR UPDATE ON public.nomen
  FOR EACH ROW
  EXECUTE PROCEDURE func_trigger_nomen();
-- End of trigger part

INSERT INTO public.nomenclature (nomenclature, geom) VALUES (42, ST_GeomFromText('POLYGON((0 0, 0 2, 2 2, 2 0, 0 0))'));
INSERT INTO public.nomen (geom) VALUES (ST_GeomFromText('POINT(1 1)'));
SELECT * FROM public.nomen;
0

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.