阿雷迪做到了……
我做了什么:为了桌子categories
CREATE TABLE categories (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(100), parent NUMERIC)
创建的表categories_closure
(所有 SQL 语句都用于 SQLite):
CREATE TABLE categories_closure (parent NUMERIC, child NUMERIC, depth NUMERIC)
接下来,创建了一些触发器来自动化我的闭包表
CREATE TRIGGER categories_delete AFTER DELETE ON categories
BEGIN
DELETE FROM categories_closure WHERE child=OLD.id;
UPDATE categories SET parent=OLD.parent WHERE parent=OLD.id;
END;
CREATE TRIGGER categories_insert AFTER INSERT ON categories
BEGIN
INSERT INTO categories_closure (parent, child, depth) VALUES (NEW.id, NEW.id, 0);
INSERT INTO categories_closure (parent, child, depth)
SELECT p.parent, c.child, p.depth+c.depth+1
FROM categories_closure p, categories_closure c
WHERE p.child=NEW.parent AND c.parent=NEW.id;
END;
CREATE TRIGGER categories_update AFTER UPDATE OF id,parent ON categories
BEGIN
DELETE FROM categories_closure WHERE child=OLD.id;
INSERT INTO categories_closure (parent, child, depth) VALUES (NEW.id, NEW.id, 0);
INSERT INTO categories_closure (parent, child, depth)
SELECT p.parent, c.child, p.depth+c.depth+1
FROM categories_closure p, categories_closure c
WHERE p.child=NEW.parent AND c.parent=NEW.id;
UPDATE categories SET parent=NEW.id WHERE parent=OLD.id;
END;
现在我可以通过简单的查询获取所有父类别的字符串,我创建了一个视图
CREATE VIEW categories_resolved AS
SELECT
id,
group_concat(name, ' ') AS fullname,
group_concat(parent) AS branch
FROM (
SELECT
c.id,
cc.parent,
c2.name
FROM categories c
LEFT JOIN categories_closure cc ON c.id=cc.child
LEFT JOIN categories c2 ON c2.id=cc.parent
ORDER BY cc.depth DESC
)
GROUP BY id
ORDER BY id ASC
最后我在关系中使用了这个视图QSqlRelationalTableModel
而不是categories
表。简单,无需创建模型、视图、代理、委托或修改 Qt 类的代码。