我有一个像这样的 postgres 架构:
CREATE TABLE categories (
category_id uuid NOT NULL PRIMARY KEY DEFAULT uuid_generate_v4(),
parent_id uuid REFERENCES categories(category_id) ON DELETE CASCADE,
image_url text,
name text NOT NULL,
description text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (parent_id, name)
);
这同样可以是任何 SQL 语言。
关于如何从路径中获取
categories
记录的普遍共识是什么?似乎这是人们一直在使用的东西,但我找不到这方面的资源。
从 URL 中说出
motorcyles/wheels/tires
...我需要从该信息中获取类别...
我正在考虑制作一个疯狂的sql函数,它会从路径返回category_id,但这看起来很复杂......
谢谢,
J
看起来甚至wordpress只是在php中执行此操作,所以我想编写sql函数会更有效。
我最终选择了这个:
CREATE OR REPLACE FUNCTION get_category_by_path(category_path text)
RETURNS categories AS $$
DECLARE
path_elements text[];
current_parent_id uuid := NULL;
current_record categories;
BEGIN
path_elements := string_to_array(category_path, '/');
FOR i IN 1..array_length(path_elements, 1) LOOP
-- Grab each category from parent to child
SELECT * INTO current_record
FROM categories
WHERE slug = path_elements[i]
AND (
parent_id = current_parent_id
OR (i = 1 AND parent_id IS NULL)
);
IF NOT FOUND THEN
RAISE EXCEPTION 'No category found for path: %', category_path;
END IF;
current_parent_id := current_record.category_id;
END LOOP;
RETURN current_record;
END;
$$ LANGUAGE plpgsql;